#include"Myhttpserver.h"
myHttpServer * myhttpserver;
#include <log.h>
#include <updatebyme.h>
String myHttpServer::getnetData()
{
    if (!isinit)
    {
        return "1989-03-27 00:00:01";
    }

   //http->beginRequest();
    int timetryget = 0;
    labelloop:
    // write_log(log_path,100,"http->get11111");
    
    int err = http1->get(Http_Date_Path);
    if (err != 0)
    {
      //  SerialMon.println(F("Date failed to connect"));
        // delay(10000);
        
        write_log(log_path,100,"Date failed to connect"+String(err));
        vTaskDelay(10000);
        
        
        return "1989-03-27 00:00:01";
        esp_restart();
    }
    // write_log(log_path,100,"http->responseStatusCode222");
    int status = http1->responseStatusCode();
    if (!status)
    {
        vTaskDelay(10000);
       
        return "1989-03-27 00:00:01";
    }

    //  SerialMon.println(F("Response Headers:"));
    // write_log(log_path,100,"http->headerAvailable333");
    int times_try = 0;
    while (http1->headerAvailable())
    {

        if(times_try > 50) 
        {
            // write_log(log_path,100,"http->headerAvailable failed ...");
            http1->stop();
            if (timetryget++ > 5)
            {
                //  write_log(log_path,100,"http->headerAvailable failed than 5 times ... return error");
               return "1989-03-27 00:00:01";
            }
   
            
            goto labelloop;
        }
        // write_log(log_path,100,"http->readHeaderName");
        String headerName = http1->readHeaderName();
        // write_log(log_path,100,"http->readHeaderValue");
        String headerValue = http1->readHeaderValue();
        // write_log(log_path,100,String(times_try)+"http->headerName "+headerName);
        // write_log(log_path,100,String(times_try)+"http->headerValue "+headerValue);
        // SerialMon.println("Date:    " + headerName + " : " + headerValue);
        vTaskDelay(100);
        times_try++;
    }
    // write_log(log_path,100,"http->isResponseChunked4444");
    if (http1->isResponseChunked())
    {
        // SerialMon.println(F("Date The response is chunked"));
    }
 
    String body = http1->responseBody();
    http1->stop();
        write_log(log_path,100,body);
    return body;
}

bool myHttpServer::UpdateData(String path, char *str, size_t lenth, String Contenttype )
{
    if (!isinit)
    {
        return false;
    }
   // Serial.println("start put data to "+path);
    write_log_def(10,"start put data to "+path);
    http1->beginRequest();
    http1->post(path);
    if (Contenttype != "")
    {
        http1->sendHeader(HTTP_HEADER_CONTENT_TYPE, Contenttype);

        /* code */
    }
   
    http1->sendHeader(HTTP_HEADER_CONTENT_LENGTH, lenth);
    http1->endRequest();
    int err = http1->write((const byte *)str, lenth);
    delay(100);
   // Serial.print("send date size");
   // Serial.println(err);
   write_log_def(10,"send date size"+String(err));

      /*
    for (size_t i = 0; i < lenth; i++)
     {
         Serial.print("0x");
        Serial.print(str[i],HEX);
         Serial.print(" ");
                    if (i%20==0)
                  {
                    Serial.println(" ");
                   
                  }
     }
    */
    // http->write((const byte*)IS1Sensor.UpData, IS1Sensor.SensorInfo.BandNum*2);
    // http->stop();
    //Serial.println("hear1");
    if (err == 0)
    {
        http1->stop();
        return false;
    }
    int status = http1->responseStatusCode();
      // Serial.println("hear3");
    if (!status)
    {
        http1->stop();
        return false;
    }

    int length = http1->contentLength();
      // Serial.println("hear4");
    if (length == 0)
    {
        http1->stop();
        return false;
    }

    String body = http1->responseBody();
   // Serial.println("body:"+body);
    write_log_def(10,"body:"+body);
    if (body != "ok")
    {
        http1->stop();
        return false;
    }

    http1->stop();
    return true;
}
void myHttpServer::ReuploadData(String path, String webpath, String content )
{
    if (!isinit)
    {
        return;
    }


    vTaskDelay(1);
    Vector<String> files;
    String vec[20]; //每次处理20个
    files.setStorage(vec);
    sdcard::lock();
    bool hasmore = !sdcard::ListDir(path.c_str(), files);
    sdcard::unlock();
    while (hasmore)
    {
        sdcard::lock();
        if (files.size() != 0)
        {

            


          //  Serial.println("find " + String(files.size()) + "file");
            write_log_def(10,"find " + String(files.size()) + "file");
            for (size_t i = 0; i < files.size(); i++)
            {
                            //判断是否时md5文件 如果是则跳过
            if (files.at(0).endsWith(".md5"))
            {
                continue;
            }
            //判断filename.md5是否存在 如果存在则读取md5并计算文件的md5进行对比
            if (!sdcard::fileexists((files.at(i) + ".md5").c_str()))
            {
                continue;

            }
            String md5value=sdcard::ReadFileToString((files.at(i) + ".md5").c_str());
            if (md5value=="")
            {
                continue;
                /* code */
            }
            //计算文件的md5

            
            
            


                File nowfile = SD_MMC.open(files.at(i).c_str(), "rb");
                size_t size = nowfile.size();
                char *arr = new char[size];
                nowfile.readBytes(arr, size);
                MD5Builder md5my;
                md5my.begin();
                md5my.add((uint8_t *)arr, size);
                md5my.calculate();
                String md5string = md5my.toString();
                if (md5string != md5value)
                {
                    // Serial.println("file md5 not match ,skip this file"+files.at(i));
                    write_log_def(10,"file md5 not match ,skip this file"+files.at(i));
                    delete[] arr;
                    sdcard::deleteFolderOrFile(files.at(i).c_str());
                    continue;
                    /* code */
                }



                bool flagsucc = UpdateData(webpath, arr, size, content);
                if (!flagsucc)
                {
                    return;
                    /* code */
                }
                delete[] arr;
                sdcard::deleteFolderOrFile(files.at(i).c_str());
                vTaskDelay(1);
                /* code */
            }
        }
        hasmore = !sdcard::ListDir(path.c_str(), files);
        sdcard::unlock();
        vTaskDelay(1);
        
    }
    if (files.size() != 0)
    {
        sdcard::lock();
        // Serial.println("find " + String(files.size()) + "file not enough 20");
        write_log_def(10,"find " + String(files.size()) + "file not enough 20");
        for (size_t i = 0; i < files.size(); i++)
        {
             vTaskDelay(1);
            File nowfile = SD_MMC.open(files.at(i).c_str(), "rb");
            size_t size = nowfile.size();
            char *arr = new char[size];
            nowfile.readBytes(arr, size);
            
            write_log_def(10,"run here now 123");
             vTaskDelay(1);
            bool flagsucc = UpdateData(webpath, arr, size, content);
            if (!flagsucc)
            {
                return;
                /* code */
            }

            delete[] arr;
            sdcard::deleteFolderOrFile(files.at(i).c_str());
            /* code */
        }
        sdcard::unlock();
    }
    vTaskDelay(1);
}

void Reuploaddata1(void *) //重新上传数据
{
    
    myhttpserver->ReuploadData("/down", Http_Sepctral_Path);
    myhttpserver->ReuploadData("/up", Http_Sepctral_Path);
    myhttpserver->ReuploadData("/other", Http_Wind_Path, "application/json");
    
}
void Reuploaddata2() //重新上传数据
{
    // sdcard::lock();
    myhttpserver->ReuploadData("/down", Http_Sepctral_Path);
    myhttpserver->ReuploadData("/up", Http_Sepctral_Path);
    myhttpserver->ReuploadData("/other", Http_Wind_Path, "application/json");
    // sdcard::unlock();
}

void myHttpServer::setup1(Client &client,char * serveradd)
{

    http1 = new HttpClient(client, serveradd,800);

    isinit = true;
    log_path = "/httplog.txt";
    myhttpserver= this;
        //  Serial.println("start httpserver 2332213"+String(http1->iServerName));
    write_log_def(10,"start httpserver: "+String(http1->iServerName));
}
