#include "LtrCrateInfo.h"
#include "LtrdConnection.h"

LtrCrateInfo::LtrCrateInfo(int intface, const CHAR* serial, LtrdConnection *parent):
    QObject(parent), m_fnd(1), m_con(parent) {
    memset(&m_descr, 0, sizeof(m_descr));
    memset(&m_stat, 0, sizeof(m_stat));
    memset(&m_mod_stat, 0, sizeof(m_mod_stat));

    strncpy(m_serial, serial, sizeof(m_serial));
    m_serial[sizeof(m_serial)-1] = '\0';
    m_intface = intface;
    m_supportModuleNames = parent->supportModuleNames();
}

void LtrCrateInfo::setStat(TLTR_CRATE_STATISTIC *stat) {
    QMutexLocker locker(&m_mutex);
    m_stat = *stat;
    m_intface = stat->crate_intf;
}

void LtrCrateInfo::setModStat(TLTR_MODULE_STATISTIC *mstat, int slot) {
    QMutexLocker locker(&m_mutex);
    if (slot < m_stat.modules_cnt) {
        m_mod_stat[slot] = *mstat;
    }
}

QString LtrCrateInfo::serial() {
    QMutexLocker locker(&m_mutex);
    return QString::fromLatin1(m_serial);
}

QString LtrCrateInfo::typeName() {
    QMutexLocker locker(&m_mutex);
    return QString(m_descr.crate_type_name);
}

quint16 LtrCrateInfo::type() {
    return m_stat.crate_type;
}

QString LtrCrateInfo::infoString() {
    return typeName() + " (" + serial() + ")";
}

int LtrCrateInfo::crateInterface() const {
    return m_intface;
}

TLTR_CRATE_STATISTIC LtrCrateInfo::stat() {
    QMutexLocker locker(&m_mutex);
    return m_stat;
}

TLTR_MODULE_STATISTIC LtrCrateInfo::mstat(int slot) {
    QMutexLocker locker(&m_mutex);
    if (slot < m_stat.modules_cnt)
        return m_mod_stat[slot];
    else
        return TLTR_MODULE_STATISTIC();
}

QString LtrCrateInfo::moduleName(int slot) {
    QMutexLocker locker(&m_mutex);
    return m_supportModuleNames ? QString::fromLatin1(m_mod_stat[slot].name) : LTR_CRATE_NAME + QString::number(m_mod_stat[slot].mid&0xFF);
}

TLTR_CRATE_DESCR LtrCrateInfo::descr() {
    QMutexLocker locker(&m_mutex);
    return m_descr;
}

int LtrCrateInfo::openConnection(TLTR *hcrate) {
    return LTR_OpenCrate(hcrate, ltrd()->addr().toIPv4Address(),
                         ltrd()->port(), crateInterface(),
                         serial().toLatin1());
}
