#include "settings.h"
#include <qrgb.h>
#include <bits/stdc++.h>
using namespace std;
Settings::Settings()
{
    m_configFile.clear();
    m_HMIconfigFile.clear();
}

void Settings::loadSetting(QString configfile)
{
    if (configfile.isEmpty() == false)
    {
        m_configFile = configfile;
    }

    fillDefaultColor();
}
void Settings::loadHMISetting(QString configfile)
{
    if (configfile.isEmpty() == false)
    {
        m_HMIconfigFile = configfile;
    }
}

//写入值到ini文件
void Settings::writeToIniFile(QString key, QVariant value)
{
    if(m_configFile.length() <= 0){return;}
    QSettings iniSetting(m_configFile, QSettings::IniFormat);
    iniSetting.setValue(key,value);
    //qDebug()<<"key"<<key;

#ifdef Q_OS_LINUX
    system("sync");
#endif
}

//写入值到ini文件
void Settings::writeToInHMIiFile(QString key, QVariant value)
{
    if(m_HMIconfigFile.length() <= 0){return;}
    QSettings iniSetting(m_HMIconfigFile, QSettings::IniFormat);
    iniSetting.setValue(key,value);
    //qDebug()<<"key"<<key;

#ifdef Q_OS_LINUX
    system("sync");
#endif
}

QVariant Settings::readFromIniFile(QString key)
{
    if(m_configFile.length() <= 0){return -1;}
    QSettings iniSetting(m_configFile, QSettings::IniFormat);
    return iniSetting.value(key);
}

//从HMIini文件读取值
QVariant Settings::readFromInHMIiFile(QString key)
{
    if(m_HMIconfigFile.length() <= 0){return -1;}
    QSettings iniSetting(m_HMIconfigFile, QSettings::IniFormat);
    return iniSetting.value(key);
}

bool Settings::ifKeyExists(QString key)
{
    if(key.length() <= 0){return false;}
    if(m_configFile.length() <= 0){return false;}
    QSettings iniSetting(m_configFile, QSettings::IniFormat);
    return iniSetting.contains(key);
}

bool Settings::ifHMIKeyExists(QString key)
{
    if(m_HMIconfigFile.length() <= 0){return false;}
    QSettings iniSetting(m_HMIconfigFile, QSettings::IniFormat);
    return iniSetting.contains(key);
}
//hsb转换成rgb
void  Settings::HSItoRGB(float h,float s,float i,float *r,float *g,float *b)
{
    int hi = ((int)h / 60) % 6;
    float f = h / 60 - hi;
    float p = i * (1 - s);
    float q = i * (1 - f * s);
    float t = i * (1 - (1 - f) * s);
    switch(hi)
    {
    case 0:
        *r = i; *g = t; *b = p;
        break;
    case 1:
        *r = q; *g = i; *b = p;
        break;
    case 2:
        *r = p; *g = i; *b = t;
        break;
    case 3:
        *r = p; *g = q; *b = i;
        break;
    case 4:
        *r = t; *g = p; *b = i;
        break;
    case 5:
        *r = i; *g = p; *b = q;
        break;
    default:
        break;
    }
    *r = (int)((*r) * 255);
    *g = (int)((*g) * 255);
    *b = (int)((*b) * 255);
}

void Settings::fillDefaultColor()
{
    m_colorRGB.clear();
#if (1)
    vector<pair<float, float> >  sbv;
    sbv.push_back(make_pair(1, 0.7));       //尾部插入数字
    sbv.push_back(make_pair(0.82, 0.7));
    sbv.push_back(make_pair(0.64, 0.7));
    sbv.push_back(make_pair(0.46, 0.7));
    sbv.push_back(make_pair(0.28, 0.7));
    sbv.push_back(make_pair(0.1, 0.7));     // 灰色单独处理,不调用此处的值
    sbv.push_back(make_pair(0.1, 1));
    sbv.push_back(make_pair(0.28, 1));
    sbv.push_back(make_pair(0.46, 1));
    sbv.push_back(make_pair(0.64, 1));
    sbv.push_back(make_pair(0.82, 1));
    sbv.push_back(make_pair(1, 1));

    float hv[] = {0, 15.6, 31.3, 46.9, 62.6, 78.2, 93.9, 109.5, 125.2, 140.8, 156.5, 172.1, 187.8, 203.4, 219.1, 234.7, 250.4, 266.0, 281.7, 297.3, 313.0, 328.6, 344.3, 360.0};
    QRgb rgb[EMB_MC_SW_ND];
    int num = 0;
    for(int i = 0; i < 12; i ++)
    {
        if (i == 5)
        {// 显示灰色
            for(int j = 0; j < 24; j ++)
            {
                rgb[num ++] = qRgb((255-j*(255/24)), (255-j*(255/24)),(255-j*(255/24)));
            }
        }
        else
        {// 显示彩色
            float s = sbv[i].first;
            float b = sbv[i].second;
            for(int j = 0; j < 24; j ++)
            {
                if(j==24)
                {
                    float R = 225;
                    float G = 225;
                    float B = 225;
                    HSItoRGB(hv[j], s, b, &R, &G, &B);
                    rgb[num ++] = qRgb(R, G, B);
                }
                else
                {

                    float R, G, B;
                    HSItoRGB(hv[j], s, b, &R, &G, &B);
                    rgb[num ++] = qRgb(R, G, B);
                }
            }
        }
    }

    for (int i = 0; i < EMB_MC_SW_ND; i++)
    {
        m_colorRGB.append((char*)(&(rgb[i])), sizeof(QRgb));
    }

#else
    u8 r, g, b;
    u8 * prgb;
    const int cnum = 243;   // 3的5次方
    int rcount = 0;
    int gcount = 0;
    int bcount = 0;
    int temp;
    r = 102;
    g = 255;
    b = 154;
    for (int i = 0; i < cnum; i++)
    {
        if ((rcount <= gcount) && (rcount <= bcount))
        {
            prgb = &r;
            rcount++;
            rcount %= 5;
        }
        else if ((gcount <= rcount) && (gcount <= bcount))
        {
            prgb = &g;
            gcount++;
            gcount %= 5;
        }
        else if ((bcount <= rcount) && (bcount <= gcount))
        {
            prgb = &b;
            bcount++;
            bcount %= 5;
        }
        else
        {
            break;
        }
        temp = *prgb;
        temp += (int)(51.2*3 + 0.5);
        if (temp > 255)
        {
            temp -= 256;
        }
        *prgb = temp;

        m_colorRGB.append(r);
        m_colorRGB.append(g);
        m_colorRGB.append(b);
        m_colorRGB.append(255);
    }
#endif
}

void Settings::writeToCsv(QString strText,int type)
{   
    QString filePath;
    filePath.clear();

    QDir apppath(qApp->applicationDirPath());
    if(type == TYPE_ERROR)
    {
        filePath = apppath.path() + apppath.separator() + CSV_ERROR;
    }
    else if(type == TYPE_BREAK)
    {
        filePath = apppath.path() + apppath.separator() + CSV_BREAK;
    }
    else if(type == TYPE_DEBUGINFO)
    {
        filePath = apppath.path() + apppath.separator() + CSV_DEBUGINFO;
    }
    if(filePath.length() <= 0){return;}

    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
    {
        QString strCurTime = QDateTime::currentDateTime().toString("yyyy/MM/dd/hh:mm:ss");//时间
        QString strMessage;
        QTextStream in(&file);//写
        if(type == TYPE_DEBUGINFO)
        {
            strMessage = QString("%1//%2").arg(strCurTime).arg(strText);//时间，内容
        }
        else
        {
            strMessage = QString("%1,%2").arg(strCurTime).arg(strText);//时间，内容
        }
        in << strMessage << '\n';

#ifdef Q_OS_LINUX
        system("sync");
#endif
        file.close();
    }
}

void Settings::clearToCsv(int type)
{
    QString filePath;
    filePath.clear();

    QStringList tempbar;
    tempbar.clear();

    QDir apppath(qApp->applicationDirPath());
    if(type == TYPE_ERROR)
    {
        filePath = apppath.path() + apppath.separator() + CSV_ERROR;
    }
    else if(type == TYPE_BREAK)
    {
        filePath = apppath.path() + apppath.separator() + CSV_BREAK;
    }
    else if(type == TYPE_DEBUGINFO)
    {
        filePath = apppath.path() + apppath.separator() + CSV_DEBUGINFO;
    }

    if(filePath.length() <= 0){return;}

    QStringList strAlarmInfoList;
    int timeFlag = 0;
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly))
    {
        QTextStream out(&file);//读
        QStringList tempOption = out.readAll().split("\n");
        // 获取系统当前时间
        QDateTime dateTime = QDateTime::currentDateTime();
        int curSecond = dateTime.toTime_t();//当前时间转换为秒
        int differSecond = curSecond-25920000;  //30天 = 2592000秒
        QDateTime newDateTime;
        for (int i = 0; i < tempOption.count(); i++)//tempOption文件里的所有行
        {
            if(type == TYPE_DEBUGINFO)
            {
                tempbar= tempOption.at(i).split("//");//获取每一行  以“//”号分开
            }
            else
            {
                tempbar = tempOption.at(i).split(",");//获取每一行  以“,”号分开
            }
            QString listTime =tempbar.at(0);
            int newTime = newDateTime.fromString(listTime, "yyyy/MM/dd/hh:mm:ss").toTime_t();//将字符串转换为秒
            //没超过30天的，存在列表里
            if(newTime >= differSecond)
            {
                tempbar.removeLast();//一共有2项（时间，内容）移除最后一项
                if (tempbar.size() > 0)
                {
                    if (tempbar.at(0).indexOf(QString("DateTime")) != -1)
                        continue;
                    strAlarmInfoList << tempOption[i];
                }
                else
                {
                    return;
                }
            }
            else
            {
                if(newTime != -1)//第一行读不到时间，newTime会等于-1
                {
                    timeFlag = 1;
                }
            }
        }
        if(timeFlag == 1)
        {
            fileClear(filePath);//清除文件内容

            for(int i =0;i<strAlarmInfoList.size();i++)
            {
                writeToCsv(strAlarmInfoList.at(i),type);
            }
        }
        if(strAlarmInfoList.size()>800)
        {
            fileClear(filePath);//清除文件内容
        }
    }
#ifdef Q_OS_LINUX
    system("sync");
#endif
    file.close();
    return;
}
QStringList Settings::readToCsv(int type)
{
    QStringList strAlarmInfoList;
    strAlarmInfoList.clear();

    QStringList strInfoList;
    strInfoList.clear();

    QStringList newTempOption;
    newTempOption.clear();

    QString allinfo;
    allinfo.clear();

    QStringList tempbar;
    tempbar.clear();

    QString filePath;//文件
    filePath.clear();

    QDir apppath(qApp->applicationDirPath());
    if(type == TYPE_ERROR)
    {
        filePath = apppath.path() + apppath.separator() + CSV_ERROR;
    }
    else if(type == TYPE_BREAK)
    {
        filePath = apppath.path() + apppath.separator() + CSV_BREAK;
    }
    else if(type == TYPE_DEBUGINFO)
    {
        filePath = apppath.path() + apppath.separator() + CSV_DEBUGINFO;
    }

    if(filePath.length() <= 0){return strAlarmInfoList;}

    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly))
    {
        QTextStream out(&file);//读

        QStringList tempOption = out.readAll().split("\n");

        for (int i = 0; i < tempOption.count(); i++)//tempOption文件里的所有行
        {
            if(type == TYPE_DEBUGINFO)
            {
                tempbar= tempOption.at(i).split("//");//获取每一行  以“//”号分开
            }
            else
            {
                tempbar = tempOption.at(i).split(",");//获取每一行  以“,”号分开
            }
            if (tempbar.size() > 0)
            {
                //DateTime不显示
                if (tempbar.at(0).indexOf(QString("DateTime")) != -1)
                    continue;
            }

            QString time = tempbar.at(0);//一共有2项（时间，内容）
            QString info ="'";

            if(time.length() > 0)
            {
                info = tempbar.at(1);
                time.remove(" ");//清除空格
                if(type == TYPE_DEBUGINFO)
                {
                    allinfo=time+"//"+info;
                }
                else
                {
                    allinfo=time+","+info;
                }
                newTempOption.append(allinfo);
                strInfoList << newTempOption[newTempOption.count()-1];
            }
        }
        for(int i = 0; i < strInfoList.count(); i++)
        {
            //if( (i != 0) && (((strInfoList.count() - 1 - i) >= 0 ) && ((strInfoList.count() - 1 - i) < strInfoList.count())))
            if( ((strInfoList.count() - 1 - i) >= 0 && ((strInfoList.count() - 1 - i) < strInfoList.count())))
            {
                strAlarmInfoList << strInfoList[strInfoList.count() -1- i]; //xcy 0313 日志倒序显示
            }
        }
    }
#ifdef Q_OS_LINUX
    system("sync");
#endif
    file.close();
    return  strAlarmInfoList;
}

//清除文件内容，不是删除文件
void Settings::fileClear(QString filePath)
{
    QFile file(filePath);
    file.open(QFile::WriteOnly|QFile::Truncate);
#ifdef Q_OS_LINUX
    system("sync");
#endif
    file.close();
}
