#include <mbus/mbus-protocol.h>
#include <mbusParserExt.h>
#include <logger.h>

#include <string.h>
#include <stdint.h>
#include <stdbool.h>



static const char NAME_VOLTAGE[] = "Voltage";
static const char NAME_CURRENT[] = "Current";
static const char NAME_POWER[] = "Power";
static const char NAME_ENERGY[] = "Energy";
static const char NAME_VOLUME[] = "Volume";
static const char NAME_UNKNOWN[] = "unknown";

static const char UNIT_VOLT[] = "V";
static const char UNIT_AMPERE[] = "A";
static const char UNIT_WATT[] = "W";
static const char UNIT_WATTHOUR[] = "Wh";
static const char UNIT_QUBICMETER[] = "m3";
static const char UNIT_UNKNOWN[] = "?";

static parsedVIB_t parseVIB_FB(mbus_value_information_block vib) {
    parsedVIB_t parsedVIB = { .name = NAME_UNKNOWN, .unit = UNIT_UNKNOWN, .exponent = 1, .found = false };

    coloredMsg(LOG_RED, true, "mpe pvd_fb unknown vife 0x%02x", vib.vife[0]);

    return parsedVIB;
}

static parsedVIB_t parseVIB_FD(mbus_value_information_block vib) {
    parsedVIB_t parsedVIB = { .name = NAME_UNKNOWN, .unit = UNIT_UNKNOWN, .exponent = 1, .found = false };

    if ((vib.vife[0] & 0b01110000) == 0b01000000) {
        parsedVIB.name = NAME_VOLTAGE;
        parsedVIB.unit = UNIT_VOLT;
        parsedVIB.exponent = (vib.vife[0] & 0b01111) - 9;
        parsedVIB.found = true;
    } else if ((vib.vife[0] & 0b01110000) == 0b01010000) {
        parsedVIB.name = NAME_CURRENT;
        parsedVIB.unit = UNIT_AMPERE;
        parsedVIB.exponent = (vib.vife[0] & 0b01111) - 12;
        parsedVIB.found = true;
    } else {
        coloredMsg(LOG_RED, true, "mpe pvd_fd unknown vife 0x%02x", vib.vife[0]);
    }

    return parsedVIB;
}

static parsedVIB_t parseVIB_default(mbus_value_information_block vib) {
    parsedVIB_t parsedVIB = { .name = NAME_UNKNOWN, .unit = UNIT_UNKNOWN, .exponent = 1, .found = false };

    if ((vib.vif & 0b01111000) == 0b00000000) {
        parsedVIB.name = NAME_ENERGY;
        parsedVIB.unit = UNIT_WATTHOUR;
        parsedVIB.exponent = (vib.vif & 0b0111) - 3;
        parsedVIB.found = true;
    } else if ((vib.vif & 0b01111000) == 0b00101000) {
        parsedVIB.name = NAME_POWER;
        parsedVIB.unit = UNIT_WATT;
        parsedVIB.exponent = (vib.vif & 0b0111) - 3;
        parsedVIB.found = true;
    } else if ((vib.vif & 0b01111000) == 0b00010000) {
        parsedVIB.name = NAME_VOLUME;
        parsedVIB.unit = UNIT_QUBICMETER;
        parsedVIB.exponent = (vib.vif & 0b0111) - 3;
        parsedVIB.found = true;
    } else {
        coloredMsg(LOG_RED, true, "mpe pvd unknown vif 0x%02x", vib.vif);
    }

    return parsedVIB;
}


parsedVIB_t parseVIB(mbus_value_information_block vib) {
    parsedVIB_t parsedVIB;

    if (vib.vif == 0xfb) {
        parsedVIB = parseVIB_FB(vib);
    } else if (vib.vif == 0xfd) {
        parsedVIB = parseVIB_FD(vib);
    } else {
        parsedVIB = parseVIB_default(vib);
    }

    return parsedVIB;
}

