#include <string.h>

#include "QuantityFormat.h"
#include "TChannel.h"
#include "chip.h"

QString TChannel::buildID(const QString &serialNumber, int index) {

    return serialNumber + QString(":") + (index < 10 ? QString("0") + QString::number(index) : QString::number(index));
}

TChannel::TChannel(TDevice *device, int index, uint16_t chip_id, const QString &id)
    : device(device), index(index), chip_id(chip_id), id(id), description(chip_description(chip_id)),
      shortDescription(chip_description_short(chip_id)), quantity(QUANTITY_NO_DATA),
      calibratedQuantity(QUANTITY_NO_DATA), calpoints_count(0) {
    memset(calpoints, 0xff, sizeof(calpoints)); // all NAN
}

TChannel::TChannel(TDevice *device, int index, uint16_t chip_id)
    : device(device), index(index), chip_id(chip_id), id(buildID(device->serialNumber, index)),
      description(chip_description(chip_id)), shortDescription(chip_description_short(chip_id)),
      quantity(QUANTITY_NO_DATA), calibratedQuantity(QUANTITY_NO_DATA), calpoints_count(0) {
    memset(calpoints, 0xff, sizeof(calpoints)); // all NAN
}

TChannel::TChannel(TDevice *device, const TChannel &channel)
    : device(device), index(channel.index), chip_id(channel.chip_id), id(channel.id), description(channel.description),
      shortDescription(channel.shortDescription), quantity(channel.quantity),
      calibratedQuantity(channel.calibratedQuantity), calpoints_count(channel.calpoints_count) {
    memcpy(calpoints, channel.calpoints, sizeof(calpoints));
}

TChannel::~TChannel() {}

bool TChannel::isVirtual() const { return chip_id >= 256; }

unit_t TChannel::getNativeUnit() const { return chip_native_unit(chip_id); }

void TChannel::convertUnits() {

    QuantityFormat &qtyFormat = QuantityFormat::instance();
    qtyFormat.toPreferredUnit(quantity);
    qtyFormat.toPreferredUnit(calibratedQuantity);
}

void TChannel::invalidate() {

    quantity = QUANTITY_NO_DATA;
    calibratedQuantity = QUANTITY_NO_DATA;
}
