#include "core/database/UAVDatabase.h"
#include "core/database/DatabaseConfig.h"

UAVDatabase *UAVDatabase::getInstance()
{
    static UAVDatabase db;
    return &db;
}

UAVDatabase::~UAVDatabase()
{
    close();
}

UAVDatabase::UAVDatabase()
{
    static int connectionCounter = 0;
    QString connectionName = QString("UAVDatabase_%1").arg(++connectionCounter);
    m_sqlDb = QSqlDatabase::addDatabase("QMYSQL", connectionName);
}

//添加记录
bool UAVDatabase::add(const UAV &data)
{
    DatabaseConnectionInfo dbInfo = DatabaseConfig::getInstance()->getConnectionInfo();
    if(open(dbInfo.databaseName, dbInfo.username, dbInfo.password))
    {
    beginAddFiled("uavdatabase");
    addFiled("id");
    addFiled("state");
    addFiled("ip");
    addFiled("port");
    addFiled("lon");
    addFiled("lat");
    endAddFiled();

    beginAddRow();
    addValue(data.id);
    addValue(data.state);
    addValue(data.ip);
    addValue(data.port);
    addValue(data.lon);
    addValue(data.lat);
    endAddRow();

    m_valueSql = m_valueSql.left(m_valueSql.length()-1);
    QString sql;
    sql = m_headerSql + m_valueSql;
    return exec(sql);
    }
    close();
    return false;
}

//查询位置信息的记录
Point UAVDatabase::ReturnUAVPosition(QString id)
{
    Point position;
    position.lon = 0;
    position.lat = 0;

    DatabaseConnectionInfo dbInfo = DatabaseConfig::getInstance()->getConnectionInfo();
    if(open(dbInfo.databaseName, dbInfo.username, dbInfo.password))
    {
    QSqlQuery query(m_sqlDb);

    QString strQuery;
    strQuery = "SELECT lon, lat FROM ";
    strQuery += "uavdatabase";
    strQuery += " WHERE id = ";
    strQuery += id;

    qDebug()<<strQuery;

    query.prepare(strQuery);
    bool isSuccess = query.exec();
    if(isSuccess)
    {
        while(query.next())
        {
            double lon = query.value(0).toDouble();
            double lat = query.value(1).toDouble();

            position.lon = lon;
            position.lat = lat;
        }
    }

    return position;
    }
    close();
    return position;
}

//返回状态信息
int UAVDatabase::giveInfo(QString id)
{
    int state = -1;
    DatabaseConnectionInfo dbInfo = DatabaseConfig::getInstance()->getConnectionInfo();
    if(open(dbInfo.databaseName, dbInfo.username, dbInfo.password))
    {
        QSqlQuery query(m_sqlDb);

        QString strQuery;
        strQuery = "SELECT state FROM ";
        strQuery += "uavdatabase";
        strQuery += " WHERE id = ";
        strQuery += id;

        qDebug()<<strQuery;

        query.prepare(strQuery);
        bool isSuccess = query.exec();
        if(isSuccess)
        {
            while(query.next())
            {
                state = query.value(0).toInt();
            }
        }
        return state;
    }
    close();
    return state;
}

//——————————————————私有方法————————————————————
//建立连接
bool UAVDatabase::open(const QString &dbName,const QString &userName,const QString &passwd)
{
    m_sqlDb.setHostName("localhost"); // 本地数据库 远程DB是：ipaddress
    m_sqlDb.setPort(3306); // 设置端口号
    m_sqlDb.setDatabaseName(dbName);
    m_sqlDb.setUserName(userName);
    m_sqlDb.setPassword(passwd);

    if(!m_sqlDb.open())
    {
        qDebug()<<"连接失败！";
        return false;
    }
    else
    {
        qDebug()<<"连接成功！";
        return true;
    }
}


void UAVDatabase::close()
{
    m_sqlDb.close();
}



void UAVDatabase::beginAddFiled(const QString &tableName)
{
    m_tableName = tableName;
    m_fieldName.clear();
    m_headerSql.clear();
    m_valueSql.clear();
    m_fieldAdd = 0;
}

void UAVDatabase::addFiled(const QString &filedName)
{
    m_fieldName.append(filedName);
}

void UAVDatabase::endAddFiled()
{
    m_headerSql = QString("INSERT INTO %0 (%1) values").arg(m_tableName).arg(m_fieldName.join(","));
}

void UAVDatabase::beginAddRow()
{
    m_valueSql += "(";
}

void UAVDatabase::addValue(const QVariant &value)
{
    m_valueSql += QString("\'%0\',").arg(value.toString());
    m_fieldAdd++;
}

void UAVDatabase::endAddRow()
{
    m_valueSql = m_valueSql.left(m_valueSql.length() - 1);
    m_valueSql += "),";
}


bool UAVDatabase::exec(const QString &sql)
{
    QSqlQuery query(m_sqlDb);
    bool success = query.exec(sql);
    return success;
}

