#include "flashtarget.h"
#include <QApplication>
#include <QSettings>
#include <QFileInfo>
#include <QDebug>

// cursor pointer used to ensure a single instance of the class.
flashTargetClass* flashTargetClass::s_instance = 0;

/* This function is called to create an instance of the class.
 *   Calling the constructor publicly is not allowed. The constructor
 *   is private and is only called by this Instance function.
 */
flashTargetClass* flashTargetClass::instance()
{
    // Only allow one instance of class to be generated.
    if (!s_instance)
        s_instance = new flashTargetClass;
    return s_instance;
}

flashTargetClass::flashTargetClass()
{
    target_filedb = QApplication::applicationDirPath()+'/'+fileNameTarget;
}

flashTargetClass::~flashTargetClass()
{

}


targetItem flashTargetClass::getTarget(unsigned int _idx)
{
    return listTargets[_idx];
}

/********************************************************
 *  Read targets from file ini
 *  Input parameters:
 *  Results:    true if ok
 *              false if error
 */
bool flashTargetClass::readTargets()
{
    listModels.clear();
    listTargets.clear();

    if(!QFileInfo::exists(target_filedb))
    {
        return false;
    }

    QSettings config(target_filedb, QSettings::IniFormat);

    //DEFAULT SECTION
    config.beginGroup("default");
    def_ip          = config.value("ip", QString("192.168.2.100")).toString();
    def_port        = config.value("port", 69).toUInt();
    def_target      = config.value("defTarget", QString("TGT-0")).toString();
    config.endGroup();

    //TARGET GROUP
    QStringList groups=config.childGroups();
    QString idModel = "";

    foreach(QString g, groups)
    {
        if (g.startsWith("MODEL", Qt::CaseInsensitive))
        {
            modelItem entry_model;
            config.beginGroup(g);

            entry_model.idModel                 = config.value("idModel").toString();
            entry_model.byte3_4                 = config.value("3_4Byte", 0).toInt();
            entry_model.description             = config.value("description").toString();
            entry_model.g                       = g;
            entry_model.model                   = config.value("model").toString();
            entry_model.numSector               = config.value("numSector", 128).toInt();
            entry_model.type                    = config.value("type", 0).toInt();
            entry_model.goldenAddressStopArea   = config.value("goldenAddressStopArea", QString()).toString();
            entry_model.goldenAddressStartArea  = config.value("goldenAddressStartArea", QString()).toString();
            entry_model.userAddressStartArea    = config.value("userAddressStartArea", QString()).toString();
            entry_model.userAddressStopArea     = config.value("userAddresStopArea", QString()).toString();
            entry_model.testAddress             = config.value("testAddress", QString()).toString();

            config.endGroup();

            listModels.append(entry_model);
        }
        else
        if (g.startsWith("TGT", Qt::CaseInsensitive))
        {

            targetItem entry_target;

            config.beginGroup(g);

            entry_target.g                    = g;
            entry_target.idTgt                = config.value("idTgt").toString();
            entry_target.description          = config.value("description").toString();
            entry_target.slotAddress          = config.value("slotAddress", QString()).toString();
            entry_target.arch                 = config.value("arch", QString("?")).toString();
            entry_target.name                 = config.value("name", QString("CPU")).toString();
            entry_target.filePrefix           = config.value("filePrefix").toString();
            idModel                           = config.value("idModel", 0).toString();

            if (!copyDataFromModel(&(entry_target.model), idModel))
                qDebug()<<"model : "<<idModel<<" not found!";
            else
                entry_target.idModel = idModel;

            config.endGroup();

            listTargets.append(entry_target);
        }
    }

    qDebug()<<"models :"<<listModels.count();
    qDebug()<<"targets :"<<listTargets.count();

    return true;
}

bool flashTargetClass::writeTargets()
{

}


QStringList flashTargetClass::getInfoLists()
{
    QStringList list;
    QString msg;
    for (int i = 0; i<listTargets.count(); i++)
    {
        msg = QString("%1 - %2").arg(listTargets[i].name).arg(listTargets[i].slotAddress);
        list.append(msg);
    }

    return list;
}

QString flashTargetClass::getDefIp()
{
    return def_ip;
}

unsigned int flashTargetClass::getDefPort()
{
    return def_port;
}

QString flashTargetClass::getDefTarget()
{
    return def_target;
}

modelItem* flashTargetClass::getModel(QString _idModel)
{
    for (int i = 0; i<listModels.count(); i++)
    {
        if (listModels[i].idModel==_idModel)
            return &listModels[i];
    }
    return 0;
}

bool flashTargetClass::copyDataFromModel(modelItem * _model, QString _idModel)
{
    modelItem *modelData = getModel(_idModel);
    if (modelData==0)
        return false;

    _model->byte3_4                 = modelData->byte3_4;
    _model->description             = modelData->description;
    _model->g                       = modelData->g;
    _model->idModel                 = modelData->idModel;
    _model->model                   = modelData->model;
    _model->numSector               = modelData->numSector;
    _model->type                    = modelData->type;
    _model->goldenAddressStopArea   = modelData->goldenAddressStopArea;
    _model->goldenAddressStartArea  = modelData->goldenAddressStartArea;
    _model->userAddressStartArea    = modelData->userAddressStartArea;
    _model->userAddressStopArea     = modelData->userAddressStopArea;
    _model->testAddress             = modelData->testAddress;

    return true;
}

unsigned int flashTargetClass::countTarget()
{
    return listTargets.count();
}

unsigned int flashTargetClass::countModel()
{
    return listModels.count();
}

const targetItem* flashTargetClass::getFromName(const QString& fname)
{
    for(int i=0; i<listTargets.count(); ++i)
    {
        bool match=fname.startsWith(listTargets[i].name, Qt::CaseInsensitive);
        if (match)
        {
            return &listTargets[i];
        }
    }
    return 0;
}

