#include "hotcameramodule.h"
#include "mynetmanager.h"
#include "defines.h"

#include <QDebug>
#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>

#define HOTCAMERA_URL  "/ISAPI/Event/notification/alertStream"

HotCameraModule::HotCameraModule(int id, QObject *parent) : QObject(parent)
{
    this->id = id;
    module_enabled = false;

    moduleParaReadFromFile(&para);
    net = new MyNetManager(this);
    connect(net, &MyNetManager::sigCapPicture, this, &HotCameraModule::onSavePicture);
    //2023.8.15
    //获取实时温度信号槽
    connect(net, &MyNetManager::sigGetTemperature, this, &HotCameraModule::onSaveTemperature);

    connect(net, SIGNAL(sigTempAlarm(float)), this, SLOT(onTempAlarm(float)));
    connect(net, SIGNAL(sigKeepBrokeAlarm()), this, SLOT(onConnectBrokeAlarm()));

    net->SetIp(para.IP_Adress);
    net->SetTempraturePara(para.reflectivetemperature,para.emissivity, para.distant);
    net->SetAlarmPara(para.alert, para.alarm, para.alarm_time);

    appTimer = new QTimer(this);
    connect(appTimer, SIGNAL(timeout()), this, SLOT(appTimerProcess()));
    appTimer->start(1000);

    removeTempAlarmFile();
    qDebug() << "HotCameraModule init ok " << endl;
}

HotCameraModule::~HotCameraModule()
{

}

void HotCameraModule::onSavePicture(QByteArray &d)
{
    qDebug()<<"onSavePicture\n";

    QString save_path;
    if(id == 0){
        save_path = "/home/data/IMAGE/";
    }else if(id == 1){
        save_path = "/home/data/IMAGE1/";
    }else{
        return;
    }

    QDir dir(QDir::currentPath());
    if(!dir.exists(save_path))
    {
        dir.mkdir(save_path);
        qDebug()<<QString("文件夹%1创建成功！").arg(save_path);
    }

    QDateTime dateTime = QDateTime::currentDateTime();
    QString currentdatetime = dateTime.toString("yyyyMMdd_hhmmss");

    QString pic_name = save_path + currentdatetime + "_temp.jpeg";
    QFile file(pic_name);
    if(!file.open(QIODevice::WriteOnly|QIODevice::ReadOnly))
    {
        qDebug()<<"/**********************************文件打开失败*******************************/";
        return;
    }
    file.write(d);
    uint64_t filesize = file.size();
    qDebug()<<"filesize:"<< filesize<<endl;
    file.close();

    //通知外界接收
    notifyCapPictureFinished(pic_name);

    //SaveTempPictureFileName = pic_name;
}

//2023.8.15
//存放获取的实时温度，并发出通知
void HotCameraModule::onSaveTemperature(QByteArray &d)
{
    qDebug()<<"onSaveTemperature\n";

    QString save_path;
    if(id == 0){
        save_path = "/home/data/Real-TimeTemperature.txt";
    }else if(id == 1){
        save_path = "/home/data/Real-TimeTemperature1.txt";
    }else{
        return;
    }


    QJsonParseError json_error;
    QJsonDocument doucment = QJsonDocument::fromJson(d,&json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        QJsonObject obj = doucment.object();
        QJsonObject TemperatureInfoList = obj.value("ThermometryRulesTemperatureInfoList").toObject();
        QJsonArray TemperatureInfo = TemperatureInfoList.value("ThermometryRulesTemperatureInfo").toArray();
        QJsonObject TemperatureType = TemperatureInfo[0].toObject();
        float maxTemperature = TemperatureType.value("maxTemperature").toDouble();
        float minTemperature = TemperatureType.value("minTemperature").toDouble();
        float averageTemperature = TemperatureType.value("averageTemperature").toDouble();
        QFile file(save_path);
        if(!file.open(QIODevice::WriteOnly|QIODevice::ReadOnly))
        {
            qDebug()<<"/**********************************文件打开失败*******************************/";
            return;
        }
        QTextStream setTemperature_data(&file);
        setTemperature_data << maxTemperature     <<endl
                            << minTemperature     <<endl
                            << averageTemperature <<endl;

        uint64_t filesize = file.size();
        qDebug()<<"filesize:"<< filesize<<endl;
        file.close();
    }
    else
    {
        qDebug() << QString("Temperature文件Json读取失败!");

    }

    return;

//    QDateTime dateTime = QDateTime::currentDateTime();
//    QString currentdatetime = dateTime.toString("yyyyMMdd_hhmmss");
//    QString pic_name = save_path + currentdatetime + "_temp.jpeg";
//    QFile file(pic_name);
//    if(!file.open(QIODevice::WriteOnly|QIODevice::ReadOnly))
//    {
//        qDebug()<<"/**********************************文件打开失败*******************************/";
//        return;
//    }
//    file.write(d);
//    uint64_t filesize = file.size();
//    qDebug()<<"filesize:"<< filesize<<endl;
//    file.close();

//    //通知外界接收
//    notifyCapPictureFinished(pic_name);
}

void HotCameraModule::onTempAlarm(float temp)
{
    Q_UNUSED(temp);
    qDebug()<< "onTempAlarm";
    TempAlarmFlag = true;
    net->GetPicture();

    //获取图片同时获取实时温度
    net->GetRealTimeTemperature();
}

void HotCameraModule::onConnectBrokeAlarm()
{
    QString save_file;
    if(id == 0){
        save_file = "/home/data/Pop_rxy1.txt";
    }else if(id == 1){
        save_file = "/home/data/Pop_rxy2.txt";
    }

    QFile file(save_file);
    if (file.open(QFile::WriteOnly))
    {
        QTextStream s(&file);
        qDebug()<< QString("onConnectBrokeAlarm =>  save %1.").arg(save_file);
    }
    file.close();
}

void HotCameraModule::moduleParaReadFromFile(HotCameraPara *p)
{
    QString para_file;
    if(id == 0){
        para_file = "/home/data/camera.txt";
    }else if(id == 1){
        para_file = "/home/data/camera1.txt";
    }else{
        return;
    }

    QFile file(para_file); //文件路径
    if (file.open(QFile::ReadOnly))
    {
        QTextStream in(&file);
        p->IP_Adress = in.readLine();
        qDebug()<<QString("IP_Adress %1").arg( p->IP_Adress);
        p->month = in.readLine().toInt();
        qDebug()<<QString("month %1").arg( p->month);
        p->week = in.readLine().toInt();
        qDebug()<<QString("week %1").arg( p->week);
        p->day = in.readLine().toInt();
        qDebug()<<QString("day %1").arg( p->day);

        QString temp = in.readLine();
        qDebug()<<QString("temp ")<<temp;
        QString hours =temp.left(temp.length()-2);
        qDebug()<<QString("hours ")<<hours;
        QString minutes =temp.right(2);
        qDebug()<<QString("hours ")<<minutes;
        p->start_hour = hours.toUInt();
        p->start_minute = minutes.toUInt();

        temp = in.readLine();
        qDebug()<<QString("temp ")<<temp;

        hours =temp.left(temp.length()-2);
        minutes =temp.right(2);
        p->end_hour = hours.toUInt();
        qDebug()<<QString("end_hour %1").arg( p->end_hour);
        p->end_minute = minutes.toUInt();
        qDebug()<<QString("end_minute %1").arg( p->end_minute);

        p->reflectivetemperature = in.readLine().toInt();
        p->emissivity = in.readLine().toFloat();
        p->distant = in.readLine().toInt();
        p->alert = in.readLine().toInt();
        p->alarm = in.readLine().toInt();
        p->alarm_time = in.readLine().toInt();
        p->nominal_capacity = in.readLine().toInt();
        p->calculated_capacity = in.readLine().toInt();
    }
    file.close();
}

void HotCameraModule::notifyCapPictureFinished(const QString &pic_name)
{

    /*****  温度告警，存储抓图文件目录  *****/
    if(TempAlarmFlag){

        QString temp_file;
        if(id == 0){
            temp_file = "/home/data/temperature.txt";
        }else if(id == 1){
            temp_file = "/home/data/temperature1.txt";
        }

        QFile file(temp_file);
        if (file.open(QFile::WriteOnly))
        {
            QTextStream set_wifi_connect(&file);
            set_wifi_connect << pic_name;//写入温度照片路径
            qDebug()<< QString("notifyCapPictureFinished => TempAlarmFlag save %1 pic_name.").arg(temp_file);
        }
        file.close();

        TempAlarmFlag = false;

        return;
    }

    /*****  手动抓图，存储抓图文件目录  *****/
    //发送文件路径
    QString save_path_file;
    if(id == 0){
        save_path_file = "/home/data/rxy_1.txt";
    }else if(id == 1){
        save_path_file = "/home/data/rxy_2.txt";
    }
    QFile file(save_path_file);
    if (file.open(QFile::WriteOnly))
    {
        QTextStream set_wifi_connect(&file);
        set_wifi_connect << pic_name;//写入温度照片路径
        qDebug()<< QString("notifyCapPictureFinished =>  save %1 pic_name.").arg(save_path_file);
    }
    file.close();

    QString msg_file_name;
    if(id == 0){
        msg_file_name = "/home/data/rxy_can_show1.txt";
    }else if(id == 1){
        msg_file_name = "/home/data/rxy_can_show2.txt";
    }

    //发送可显示消息
    QFile file1(msg_file_name);//文件路径
    if(file1.open(QFile::WriteOnly))
    {
        QTextStream set_wifi_connect(&file1);
        set_wifi_connect<< "1";
        qDebug()<< QString("notifyCapPictureFinished =>  save %1 to show.").arg(msg_file_name);
    }
    file1.close();
}

void HotCameraModule::appTimerProcess()
{
    //qDebug() << QString("[%1]: appTimerProcess\n").arg(id);
    //时间更改检查
    //qDebug() << QString("[%1]:eventTimeChangeCheck\n").arg(id);
    eventTimeChangeCheck();

    //qDebug() << QString("[%1]:eventConnectTimeCheck\n").arg(id);
    //检测热像仪连接时间窗口，并连接
    eventConnectTimeCheck();

    //qDebug() << QString("[%1]:eventCapPictureCheck\n").arg(id);
    //检测抓图文件，并抓图
    eventCapPictureCheck();

    //2023.8.14
    //检测获取温度文件，并获取实时温度
    eventGetTemperatureCheck();

    //qDebug() << QString("[%1]:eventParaChangedCheck\n").arg(id);
    //参数更改检查
    eventParaChangedCheck();

    //连接成功，删除长连接断线告警文件
    eventConnectBrokeAlarmCheck();

    //热像仪功能关闭/打开控制
    eventConnectSwitch();
}

bool HotCameraModule::eventParaChangedCheck()
{
    QString change_set_file;

    if(id == 0){
        change_set_file = "/home/data/change_set.txt";
    }else if(id == 1){
        change_set_file = "/home/data/change_set1.txt";
    }

    QFileInfo file_set(change_set_file);
    if (file_set.exists() == true)
    {
        qDebug()<< QString("%1 changed!").arg(change_set_file);

        HotCameraPara temp;
        moduleParaReadFromFile(&temp);

        if(temp.IP_Adress != para.IP_Adress){

            qDebug() << QString("<<<<< HotCameraModule[%1] IP_Adress changed net->KeepState() =%2\n").arg(id).arg(net->KeepState());
            if(net->KeepState() == NET_CONNECTED){
                qDebug() << QString("net%1->KeepReconnect...").arg(id);
                net->KeepReconnect();
            }
        }

        if((temp.reflectivetemperature != para.reflectivetemperature) ||
                (temp.emissivity != para.emissivity) ||
                (temp.distant != para.distant)
                )
        {
            qDebug() << QString("<<<<< HotCameraModule[%1] net->SetTempraturePara...\n").arg(id);
            net->SetTempraturePara(temp.reflectivetemperature,temp.emissivity, temp.distant);
        }

        if((temp.alert != para.alert) ||
                (temp.alarm != para.alarm) ||
                (temp.alarm_time != para.alarm_time)
                )
        {
            qDebug() << QString("<<<<< HotCameraModule[%1] net->SetAlarmPara...").arg(id);
            net->SetAlarmPara(temp.alert, temp.alarm, temp.alarm_time);
        }

        memcpy(&para, &temp, sizeof(HotCameraPara));

        QFile file(change_set_file);
        file.remove();

        qDebug() << "change_set";

        return true;
    }

    return false;
}

bool HotCameraModule::eventCapPictureCheck()
{
    QString file_name;
    if(id == 0){
        file_name = "/home/data/rxy_show1.txt";
    }else if(id == 1){
        file_name = "/home/data/rxy_show2.txt";
    }else{
        return false;
    }

    QFileInfo fileInfo(file_name);
    if(fileInfo.exists() == true)
    {
        qDebug()<< QString("%1 changed, start capture picture!").arg(file_name)<<endl;
        if(module_enabled == true)
        {
            net->GetPicture();

            //获取图片同时获取实时温度
            net->GetRealTimeTemperature();
        }
        else{
        }
        QFile file1(file_name);
        file1.remove();

        return true;
    }

    return false;

}

//2023.8.15
//获取实时温度事件
bool HotCameraModule::eventGetTemperatureCheck()
{
    QString file_name;
    if(id == 0){
        file_name = "/home/data/rxy_temperature_show1.txt";
    }else if(id == 1){
        file_name = "/home/data/rxy_temperature_show2.txt";
    }else{
        return false;
    }

    QFileInfo fileInfo(file_name);
    if(fileInfo.exists() == true)
    {
        qDebug()<< QString("%1 changed, start get Temp!").arg(file_name)<<endl;

        if(module_enabled == true)
        {
            net->GetRealTimeTemperature();
        }
        else{
        }
        QFile file1(file_name);
        file1.remove();

        return true;
    }

    return false;
}

bool HotCameraModule::eventTimeChangeCheck()
{
    QString time_change_file;
    if(id == 0){
        time_change_file = "/home/data/change_time.txt";
    }else if(id == 1){
        time_change_file = "/home/data/change_time1.txt";
    }else{
        return false;
    }

    QFileInfo file_time(time_change_file);
    if (file_time.exists() == true)
    {
        qDebug()<< QString("%1 changed!").arg(time_change_file);
        //更新参数文件，时间范围值会被更新
//        HotCameraPara temp;
//        moduleParaReadFromFile(&temp);
//        memcpy(&para, & temp, sizeof(HotCameraPara));

        QFile file_change_time(time_change_file);
        file_change_time.remove();
        qDebug() << "eventTimeChangeCheck!\n" << endl;
        return true;
    }

    return false;
}

bool HotCameraModule::eventConnectTimeCheck()
{

    if(module_enabled){

        uint32_t start_minute, end_minute, now_minute;
        start_minute = para.start_hour * 60 + para.start_minute;
        end_minute = para.end_hour * 60 + para.end_minute;

#if  0
        QDateTime dateTime = QDateTime::currentDateTime();
        now_minute = dateTime.time().hour() * 60 + dateTime.time().minute();
#else
        QDateTime dateTime = QDateTime::currentDateTimeUtc();
        long nowtime = dateTime.toTime_t() + 28800;
        struct tm *timp;
        timp = gmtime(&nowtime);
        now_minute = timp->tm_hour * 60 + timp->tm_min;

#endif
        //qDebug() << QString("<<<<< HotCameraModule[%1]:").arg(id) << dateTime;
        //qDebug("<<<<< HotCameraModule[%d] :start_minute[%u],end_minute[%u],now_minute[%u]\n", id, start_minute, end_minute, now_minute);
        if(now_minute >= start_minute && now_minute <= end_minute){
            moduleConnect();
        }else{

            //qDebug("<<<<< HotCameraModule[%d] not in connect time range, disconnect!!!\n",id);
            modleDisConnect();
        }

    }else {
        //qDebug("<<<<< HotCameraModule[%d] module_enabled false disconnect!!!\n",id);
        modleDisConnect();
    }

    return true;
}

bool HotCameraModule::eventConnectBrokeAlarmCheck()
{

    if(net->KeepState() != NET_CONNECTED){
        return false;
    }

    if(removeTempAlarmFile()){
        return true;
    }
    return false;
}

bool HotCameraModule::eventConnectSwitch()
{
    QString time_change_file;
    if(id == 0){
        time_change_file = "/home/data/connect_rxy1.txt";
    }else if(id == 1){
        time_change_file = "/home/data/connect_rxy2.txt";
    }else{
        return false;
    }
    QFile file(time_change_file); //文件路径

    if (file.open(QFile::ReadOnly) == true)
    {
        QTextStream set_wifi_connect(&file);
        if(set_wifi_connect.readLine().toInt() == 1)
        {
            //打开热像仪
            module_enabled = true;
//            qDebug()<<"eventConnectSwitch_Open hot!";
        }
        else
        {
            //关闭热像仪
            module_enabled = false;
//            qDebug()<<"eventConnectSwitch_Close hot!";
        }
    }
    else{
         ;
    }
    return false;
}

void HotCameraModule::moduleConnect()
{
    if(net->KeepState() == NET_DISCONNECT){
        qDebug()<< "KeepState is NET_DISCONNECT, to KeepConnect...";
        net->KeepConnect();
    }
}

void HotCameraModule::modleDisConnect()
{
    if(net->KeepState() != NET_DISCONNECT){
         net->KeepDisconnect();
    }
}

bool HotCameraModule::removeTempAlarmFile()
{
    QString remove_file;
    if(id == 0){
        remove_file = "/home/data/Pop_rxy1.txt";
    }else if(id == 1){
        remove_file = "/home/data/Pop_rxy2.txt";
    }

    QFileInfo file_time(remove_file);
    if (file_time.exists() == true)
    {
        qDebug()<< QString("eventConnectBrokeAlarmCheck remove %1 ！\n").arg(remove_file);
        QFile file(remove_file);
        file.remove();
        return true;
    }

    return false;
}
