#include "load_file.h"
#include <stdlib.h>
#include "ec800m.h"
#include "usart.h"
#include <string.h>
#include "gd_ota_flash.h"
#include "systick.h"
#include "main.h"

#define readHttpfile(cmd, filename, time_out) sprintf(cmd, "AT+QHTTPREADFILE=\"UFS:%s\",%d\r\n", filename, time_out)
#define cmdHttpSetUrlLen(cmd,urlLen) sprintf(cmd,"AT+QHTTPURL=%d\r\n",urlLen)
#define cmdHttpGET(cmd) sprintf(cmd,"AT+QHTTPGET=100\r\n")
#define cmdReadFile(cmd,filename) sprintf(cmd,"AT+QFDWL=%s\r\n",filename)
#define cmdOpenFile(cmd,filename) sprintf(cmd,"AT+QFOPEN=\"%s\",2\r\n",filename)
#define cmdReadHTTP(cmd) sprintf(cmd,"AT+QHTTPREAD=10")
#define cmdDeletFile(cmd,filename) sprintf(cmd,"AT+QFDEL=\"UFS:%s\"\r\n",filename)


bool extract_url_and_version(char *data,char* url, char* version) ;
int update_version(BOOT_MESSAGE *old_version, const char *new_version);

int load_file_config(char *url)
{
	char cmd[50];
	//设置服务器URL len
	cmdHttpSetUrlLen(cmd,strlen(url));
	EC800MSendCmd(cmd,strlen(cmd));
	WaitResponse(RSP_CONNECT, 500);
	delay_1ms(200);
	//发送服务器url
	EC800MSendCmd(url,strlen(url));
	if(WaitResponse(RSP_OK, 500)!=true) return -1;
	delay_1ms(200);
	//向对应服务器发送get请求
	cmdHttpGET(cmd);
	EC800MSendCmd(cmd,strlen(cmd));
	if(WaitResponse("QHTTPGET:", 5000)!=true) return -1;
	delay_1ms(200);	
	
	//把请求获取的数据通过文件系统保存
	readHttpfile(cmd,"bin.txt",80);
	EC800MSendCmd(cmd,strlen(cmd));
  if(WaitResponse(RSP_OK, 5000)!=true) return -1;	
	task_fwdgt_reload();
	delay_1ms(1000);
	task_fwdgt_reload();
	delay_1ms(1000);	
	return 1;
	
}
//检查程序版本是否要升级
//参数url从此处获取程序  http://gpu.ringzle.com:8082/iot/vesion/control/getDeviceVersionInfo/DTU/4G
int check_soft_version(char *url,char *version)
{
	char versionUrl[100];
	sprintf(versionUrl,"http://gpu.ringzle.com:8082/iot/vesion/control/getDeviceVersionInfo/DTU/4G");
	
	char cmd[50];
	//设置服务器URL len
	cmdHttpSetUrlLen(cmd,strlen(versionUrl));
	EC800MSendCmd(cmd,strlen(cmd));
	WaitResponse(RSP_CONNECT, 5000);
	delay_1ms(200);
	//发送服务器url
	EC800MSendCmd(versionUrl,strlen(versionUrl));
	if(WaitResponse(RSP_OK, 5000)!=true) return -1;
	//向对应服务器发送get请求
	delay_1ms(200);
	cmdHttpGET(cmd);
	EC800MSendCmd(cmd,strlen(cmd));
	delay_1ms(100);
	if(WaitResponse("QHTTPGET", 5000)!=true) return -1;
	//读取网页响应信息
	delay_1ms(200);
	readHttpfile(cmd,"version.txt",80);
	EC800MSendCmd(cmd,strlen(cmd));
  if(WaitResponse(RSP_OK, 5000)!=true) return -1;
	delay_1ms(1000);
	cmdReadFile(cmd,"version.txt");
	EC800MSendCmd(cmd,strlen(cmd));
			task_fwdgt_reload();
	delay_1ms(1000);
	if(extract_url_and_version( (char *)&UART0_RX_BUF,url,version)!=true)return -1;
	return 1;
}


// 提取URL和版本的函数
bool extract_url_and_version(char* data, char* url, char* version) {
    char *ok_ptr, *json_start, *json_end, *url_start, *url_end, *version_start, *version_end;

    // 检查是否含有OK
    ok_ptr = strstr(data, "OK");
    if (ok_ptr == NULL) {
        return false;
    }

    // 寻找{}中的内容
    json_start = strstr(data, "{");
    if (json_start == NULL) {
        return false;
    }
    json_end = strstr(json_start, "}");
    if (json_end == NULL) {
        return false;
    }

    // 提取URL
    url_start = strstr(json_start, "\"url\":\"");
    if (url_start == NULL) {
        return false;
    }
    url_start += strlen("\"url\":\"");
    url_end = strstr(url_start, "\"");
    if (url_end == NULL) {
        return false;
    }
    strncpy(url, url_start, url_end - url_start);
    url[url_end - url_start] = '\0';

    // 提取版本
    version_start = strstr(json_start, "\"version\":\"");
    if (version_start == NULL) {
        return false;
    }
    version_start += strlen("\"version\":\"");
    version_end = strstr(version_start, "\"");
    if (version_end == NULL) {
        return false;
    }
    strncpy(version, version_start, version_end - version_start);
    version[version_end - version_start] = '\0';

    return true;
}


int update_version(BOOT_MESSAGE *old_version, const char *new_version) {
    // 解析新版本号
    char *token;
    token = strtok((char *)new_version, ".");
    uint8_t new_version_h = atoi(token);
    token = strtok(NULL, ".");
    uint8_t new_version_m = atoi(token);
    token = strtok(NULL, ".");
    uint8_t new_version_l = atoi(token);
		if(new_version_h>old_version->VERSION_H)
		{
			//发生版本更新
			old_version->VERSION_H=new_version_h;
			old_version->VERSION_M=new_version_m;
			old_version->VERSION_L=new_version_l;
			old_version->UP_FLAG=1;
			return 1;
		}
		else if(new_version_m > old_version->VERSION_M)
		{
			old_version->VERSION_H=new_version_h;
			old_version->VERSION_M=new_version_m;
			old_version->VERSION_L=new_version_l;
			old_version->UP_FLAG=1;
			return 1;
		}
		else if(new_version_l > old_version->VERSION_L)
		{
			old_version->VERSION_H=new_version_h;
			old_version->VERSION_M=new_version_m;
			old_version->VERSION_L=new_version_l;
			old_version->UP_FLAG=1;
			return 1;
		}
		else
		{
			return 0;
		}
		
}
void delete_file()
{
	char cmd[50];
	cmdDeletFile(cmd,"version.txt");
	EC800MSendCmd(cmd,strlen(cmd));
	WaitResponse(RSP_OK, 5000);
	
	cmdDeletFile(cmd,"bin.txt");
	EC800MSendCmd(cmd,strlen(cmd));
	WaitResponse(RSP_OK, 5000);
}

void check_update(void)
{
	char *bin_url=malloc(100);
	char *version=malloc(20);
		task_fwdgt_reload();	
  delete_file();
	if(check_soft_version(bin_url,version))//检查提取url
	{
			//判断两个版本号
			BOOT_MESSAGE *old_version=malloc(sizeof(BOOT_MESSAGE));
			GD32_READ_OTA(old_version);
			delay_1ms(100);
			task_fwdgt_reload();
			if(update_version(old_version,version)==1)
			{
				if(load_file_config(bin_url)==1)
				{
					//列出所有file
					delay_1ms(200);
					EC800MSendCmd("AT+QFLST=\"*\"\r\n", strlen("AT+QFLST=\"*\"\r\n"));
					if(WaitResponse("bin.txt", 100)==true)
					{
						//文件加载成功写入标志位
						write_soft_version(old_version);
						NVIC_SystemReset();
					}
				}
			}
			free(old_version);
	}
	free(bin_url);
	free(version);
}

void save_version(char *version)
{
		BOOT_MESSAGE current_version;
		char *token;
    token = strtok(version, ".");
    current_version.VERSION_H = atoi(token);
    token = strtok(NULL, ".");
    current_version.VERSION_M = atoi(token);
    token = strtok(NULL, ".");
    current_version.VERSION_L = atoi(token);
		write_soft_version(&current_version);
}