#include "prtlocalizework.h"
#include "preDefine.h"
#include "base/DB/fm_database.h"
#include "event/fmapplication.h"
#include "event/posevent.h"
#include "QsLog.h"
#include <QSqlQuery>

PrtLocalizeWork::PrtLocalizeWork(WorkObject *parentt) : WorkObject(parentt)
{
    FMDataBase db(qApp->applicationDirPath() + "/" + DEFAULT_PRTDBNAME);

    db.creat(QString("create table prtlist (prt_id varchar(80) primary key,"
                     "prt_name text,prt_type int(1),prt_config text,prt_stalls text)"), DEFAULT_PRTFORM);

    FMApplication::subscibeEvent(this, PosEvent::s_change_prt);
    FMApplication::subscibeEvent(this, PosEvent::s_delete_prt);
}

bool PrtLocalizeWork::event(QEvent *e)
{
    if(e->type() == PosEvent::s_change_prt)
    {
        QVariantMap prtinfo;

        GETEVENTINFO(prtinfo,e,QVariantMap);

        if(!(prtinfo.contains(DB_KEY_PRTID) || prtinfo.contains(DB_KEY_PRTNAME) ||
           prtinfo.contains(DB_KEY_PRTCONFIG) ||
           prtinfo.contains(DB_KEY_PRTTYPE) ||prtinfo.contains(DB_KEY_PRTSTALLS)))
        {
            QLOG_DEBUG() << "PosEvent::s_change_prt failed : " << prtinfo;
            return true;
        }

        QLOG_DEBUG() << prtinfo;

        otpPrt(prtinfo);

        return true;
    }

    if(e->type() == PosEvent::s_delete_prt)
    {
        QString prtid;

        GETEVENTINFO(prtid,e,QString);

        if(!prtid.isEmpty())
            deletePrt(prtid);

        return true;
    }

    return WorkObject::event(e);
}

void PrtLocalizeWork::deletePrt(QString prtid)
{
    FMDataBase db(qApp->applicationDirPath() + "/" + DEFAULT_PRTDBNAME);

    QSqlQuery query;

    QStringList list;
    list.append(EVENT_KEY_PRTID);

    if(!db.find(DEFAULT_PRTFORM, query, list, QString(DB_KEY_PRTID).append("='%1'").arg(prtid)))
        return ;

    if(!query.next())
    {
        QLOG_WARN() << "not found prt : " << prtid;
        return ;
    }
    else
    {
        bool flag = db.dlt(DEFAULT_DBFORM, QString(DB_KEY_PRTID).append("='%1'").arg(prtid));
        QLOG_DEBUG() << "delete prt : " << prtid << "(" << flag << ")";
    }
}

void PrtLocalizeWork::otpPrt(QVariantMap &prtinfo)
{
    FMDataBase db(qApp->applicationDirPath() + "/" + DEFAULT_PRTDBNAME);

    QString prtid = prtinfo[EVENT_KEY_PRTID].toString();

    QSqlQuery query;

    QStringList list;
    list.append(EVENT_KEY_PRTID);

    if(!db.find(DEFAULT_PRTFORM, query, list, QString(DB_KEY_PRTID).append("='%1'").arg(prtid)))
        return ;

    if(!query.next())
    {
        QLOG_DEBUG() << "insert new prt" << prtinfo;
        bool flag = db.insert(DEFAULT_PRTFORM, prtinfo);
        QLOG_DEBUG() << "insert new prt : " << prtid << "(" << flag << ")";
    }
    else
    {
        QLOG_DEBUG() << "update prt" << prtinfo;
        bool flag = db.update(DEFAULT_PRTFORM, prtinfo, QString(DB_KEY_PRTID).append("='%1'").arg(prtid));
        QLOG_DEBUG() << "update prt : " << prtid << "(" << flag << ")";
    }
}
