#include "fmp_database.h"

#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariantHash>
#include <QSqlQueryModel>
#include "QsLog.h"


FMPDataBase::FMPDataBase(QString dbname, QString connectname, QObject *parent) : QObject(parent)
{
    _dbname = dbname;
    _connectname = connectname;
}

void FMPDataBase::Init()
{
    _db = QSqlDatabase::addDatabase("QSQLITE", _connectname);
    _db.setDatabaseName(_dbname);
}

FMPDataBase::~FMPDataBase()
{
    if(_db.isOpen())
        _db.close();
}

bool FMPDataBase::creat(QString sql)
{

    if(!_db.isOpen())
        qDebug()<< "----" <<_db.open();

    qDebug() << _db.lastError().type() << _db.lastError().text();

    QSqlQuery query(_db);

    bool flag = query.exec(sql);

    if(!flag)
        QLOG_WARN() << query.lastError();

    _db.close();

    return flag;
}

bool FMPDataBase::dlt(QString table, QString condition)
{

    if(!_db.isOpen())
        qDebug()<< "----" <<_db.open();

    qDebug() << _db.lastError().type() << _db.lastError().text();


    QString sql = QString("delete from %1 where %2").arg(table, condition);

    QLOG_INFO() << "delete sql " << sql;

    QSqlQuery query(_db);

    bool flag =  query.exec(sql);

    if(!flag)
        QLOG_WARN() << query.lastError();

    _db.close();

    return flag;
}

bool FMPDataBase::insert(QString table, QVariantHash data)
{
    if(!_db.isOpen())
        qDebug()<< "----" <<_db.open();

    QString sql;
    QStringList columnnamelist;
    QStringList columnvaluelist;

    if(!getSql(table, data, columnnamelist, columnvaluelist))
    {
        return false;
    }

    QSqlQuery query(_db);

    sql = QString("insert into %1 (").arg(table) + columnnamelist.join(", ") + ") values (" + columnvaluelist.join(", ") + ")";

    QLOG_WARN() << "inset sql : " << sql;
    qDebug() << "inset sql : " << sql;

    bool flag =  query.exec(sql);

    if(!flag)
        QLOG_WARN() << query.lastError();

    _db.close();

    return flag;
}

bool FMPDataBase::update(QString table, QVariantHash data, QString condition)
{

    if(!_db.isOpen())
        qDebug()<< "----" <<_db.open();

    QString sql;

    if(!getSql(table, data, sql))
    {
        return false;
    }

    QSqlQuery query(_db);

    sql = QString("update %1 set ").arg(table) + sql + " where " + condition;

    QLOG_INFO() << "update sql : " << sql;

    bool flag =  query.exec(sql);

    if(!flag)
        QLOG_WARN() << query.lastError();

    _db.close();

    return flag;
}

bool FMPDataBase::find(QString table, QSqlQuery &query, QStringList keylist, QString condition)
{

    if(!_db.isOpen())
        qDebug()<< "----" <<_db.open();

    qDebug() << _db.lastError().type() << _db.lastError().text();


    QSqlQuery tmpquery(_db);

    QString sql = "select ";
    if(keylist.size() != 0)
        sql += keylist.join(", ");
    else
        sql += "*";

    if(condition == "")
        condition = "1=1";

    sql += QString(" from %1 where ").arg(table) + condition;

    QLOG_INFO() << "find sql : " << sql;

    bool flag =  query.exec(sql);

    if(!flag)
        QLOG_WARN() << tmpquery.lastError();

    query = tmpquery;

    _db.close();

    return flag;
}

bool FMPDataBase::getSql(QString table, QVariantHash data, QStringList& columnnamelist, QStringList& columnvaluelist)
{
    QSqlQuery query(_db);

    QString tmpsql = QString("PRAGMA table_info(%1)").arg(table);
    query.exec(tmpsql);

    while(query.next())
    {
        QString columnname = query.value(1).toString();

        if(data.contains(columnname))
        {
            /**
              *add support type;
              * */
//            switch (data.value(columnname).type()) {
//            case QVariant::Int:
//                columnnamelist.append(columnname);
//                columnvaluelist.append(QString("'") + QString::number(data.value(columnname).toInt()) + "'");
//                break;
//            case QVariant::String:
//                columnnamelist.append(columnname);
//                columnvaluelist.append(QString("'") + data.value(columnname).toString() + "'");
//                break;
//            case QVariant::Bool:
//                columnnamelist.append(columnname);
//                columnvaluelist.append(QString("'") + QString::number(data.value(columnname).toBool()? 1 : 0) + "'");
//                break;
//            default:
//                break;
//            }

              columnnamelist.append(columnname);
              columnvaluelist.append(QString("'") + data.value(columnname).toString() + "'");

        }
        continue ;
    }


    if(columnnamelist.size() == 0)
        return false;
    return true;
}

QSqlDatabase FMPDataBase::getDb() const
{
    return _db;
}

bool FMPDataBase::getSql(QString table, QVariantHash data, QString& sql)
{
    QSqlQuery query(_db);

    QString tmpsql = QString("PRAGMA table_info(%1)").arg(table);
    query.exec(tmpsql);

    QStringList list;

    while(query.next())
    {
        QString columnname = query.value(1).toString();

        if(data.contains(columnname))
        {
            /**
              *add support type(mysql/sqlserver/...);
              * */
//            switch (data.value(columnname).type()) {
//            case QVariant::Int:
//                list.append(columnname + " = '" + QString::number(data.value(columnname).toInt()) + "'");
//                break;
//            case QVariant::String:
//                list.append(columnname + " = '" + data.value(columnname).toString() + "'");
//                break;
//            case QVariant::Bool:
//                list.append(columnname + " = '" + QString::number(data.value(columnname).toBool()? 1 : 0) + "'");
//                break;
//            default:
//                break;
//            }
            /**
             * sqlite
             * */
            list.append(columnname + " = '" + data.value(columnname).toString() + "'");
        }
        continue ;
    }


    if(list.size() == 0)
        return false;

    sql = list.join(", ");

    return true;
}
