#include    "goahead.h"
#include    "libipmi_IPM.h"
#include    "com_IPMIDefs.h"
#include    "ResultUtils.h"
#include    "cJSON.h"
#include    "libipmi_storlead_OEM.h"
#include    "libsensor.h"
#include    <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
/*获取设备信息*/

/*获取设备信息*/
void getDeviceInfo(Webs *wp){
    logmsg(2, "--------------------ggggg11gggg----------------");

    uint16_t    wRet = LIBIPMI_E_SUCCESS;
    GetDevIDRes_T   DeviceID;
    struct ifreq ifreq;
    int sock;
    struct sockaddr_in *myaddr;
    IPMI20_UDS_SESSION_T    UDSSession;

    char BuildTime[30] = {0};
    char FwVersion[10] = {0};
    char MacAddr[18] = {0};
    char IpAddr[16] = {0};

    

    //Create session
    LIBIPMI_CreateSession(&UDSSession, 10);

    //get build time
    sprintf(BuildTime, "%s %s", __DATE__, __TIME__);

    //get firmware version
    wRet = IPMICMD_GetDeviceID( &UDSSession, &DeviceID, DEFAULT_TIMEOUT);
    if (wRet == LIBIPMI_E_SUCCESS)
    {
        sprintf(FwVersion, "%d.%d", DeviceID.FirmwareRevision1, DeviceID.FirmwareRevision2);
    }

    //Close session
    LIBIPMI_CloseSession(&UDSSession );

    // //get mac address
    // if((sock=socket(AF_INET,SOCK_STREAM,0))<0)
    // {
    //     printf("Get mac address socket fail!\n");
    // }
    // else
    // {
    //     strcpy(ifreq.ifr_name,"eth0");
    //     if(ioctl(sock,SIOCGIFHWADDR,&ifreq)<0)
    //     {
    //         printf("Get mac address ioctl fail!\n");
    //     }
    //     else
    //     {
    //         sprintf(MacAddr, "%02x:%02x:%02x:%02x:%02x:%02x",
    //                 (unsigned char)ifreq.ifr_hwaddr.sa_data[0],
    //                 (unsigned char)ifreq.ifr_hwaddr.sa_data[1],
    //                 (unsigned char)ifreq.ifr_hwaddr.sa_data[2],
    //                 (unsigned char)ifreq.ifr_hwaddr.sa_data[3],
    //                 (unsigned char)ifreq.ifr_hwaddr.sa_data[4],
    //                 (unsigned char)ifreq.ifr_hwaddr.sa_data[5]);
    //     }
    // }
    // close(sock);

    // //get ip address
    // strcpy(ifreq.ifr_name, "eth0");
    // if((sock=socket(AF_INET, SOCK_STREAM, 0))<0)
    // {
    //     printf("Get ip address socket fail!\n");
    // }
    // else
    // {
    //     wRet = ioctl(sock, SIOCGIFADDR, &ifreq);
    //     if(wRet < 0)
    //     {
    //         printf("Get ip address ioctl fail!\n");
    //     }
    //     else
    //     {
    //         myaddr = (struct sockaddr_in *)&(ifreq.ifr_addr);
    //         strcpy(IpAddr, inet_ntoa(myaddr->sin_addr));   
    //     }
    // }
    // close(sock);

    char *pStr = malloc(500);
    char *dataStr = malloc(200);
    char msgStr[10] = "\"\"";
    char codeStr[10] = "200";
    
    sprintf(dataStr, "{\"buildTime\":\"%s\",\"fwVersion\":\"%s\",\"macAddr\":\"%s\",\"ipAddr\":\"%s\"}", \
        BuildTime, FwVersion, MacAddr, IpAddr);

    sprintf(pStr, "{\"data\": %s,\"msg\":%s,\"code\": %s}", \
         dataStr, msgStr, codeStr);

    // int code = 200;
    // cJSON * root =  cJSON_CreateObject();
    // cJSON * data =  cJSON_CreateObject();
    // cJSON * next =  cJSON_CreateObject();
    // cJSON_AddItemToObject(root, "data", data);//根节点下添加
    // cJSON_AddItemToObject(root, "msg", cJSON_CreateString(""));
    // cJSON_AddItemToObject(root, "code", cJSON_CreateString("200"));
    // cJSON_AddStringToObject(data, "buildTime", BuildTime);
    // cJSON_AddStringToObject(data, "fwVersion", FwVersion);
    // cJSON_AddStringToObject(data, "macAddr", MacAddr);
    // cJSON_AddStringToObject(data, "ipAddr", IpAddr);

    //pStr = cJSON_Print(root);

    printf("json str:\n%s\n", pStr);
    websSetStatus(wp, 200);
    websWriteHeaders(wp, -1, 0);
    websWriteEndHeaders(wp); 
    websWrite(wp, "%s", pStr);
    websFlush(wp, 0);
    websDone(wp);

    free(pStr);
    free(dataStr);
    
}


/*获取系统信息*/
void getSysInfo(Webs *wp){
    int wRet;
    SysInfo_T sysInfo;
    uint8_t Req[5] = {0,0,0,0,0};
    uint8_t Res[MAX_TEXT_LEN+5];
    int dwResLen;
    IPMI20_UDS_SESSION_T    UDSSession;


    sysInfo.title = malloc(MAX_TITLE_LEN);
    if(sysInfo.title == NULL)
    {
        printf("---> title malloc error!\n");
        goto sys_info_end;
    }
    else
        memset(sysInfo.title, 0, MAX_TITLE_LEN);
    
    sysInfo.text = malloc(MAX_TEXT_LEN);
    if(sysInfo.text == NULL)
    {
        printf("---> text malloc error!\n");
        goto sys_info_end;
    }
    else
        memset(sysInfo.text, 0, MAX_TEXT_LEN);

    //Create session
    wRet = LIBIPMI_CreateSession(&UDSSession, 10);
    
    LIBIPMI_HL_GetSysInfo(&UDSSession, &sysInfo, DEFAULT_TIMEOUT);

    //Close session
    LIBIPMI_CloseSession(&UDSSession );

    printf("Title: %s\n", sysInfo.title);
    printf("Text: %s\n", sysInfo.text);


    cchar *pStr;
    int code = 200;
    cJSON * root =  cJSON_CreateObject();
    cJSON * data =  cJSON_CreateObject();
    // cJSON * next =  cJSON_CreateObject();
    cJSON_AddItemToObject(root, "data", data);//根节点下添加
    cJSON_AddItemToObject(root, "msg", cJSON_CreateString(""));
    cJSON_AddItemToObject(root, "code", cJSON_CreateString("200"));
    cJSON_AddStringToObject(data, "title", sysInfo.title);
    cJSON_AddStringToObject(data, "text", sysInfo.text);

    pStr = cJSON_Print(root);

    printf("first json:\n%s\n", pStr);
    logmsg(2, "-----------------------sys----------------------%s", pStr);
    websSetStatus(wp, WEBS_KEEP_ALIVE);
    websWriteHeaders(wp, -1, 0);
    websWriteEndHeaders(wp); 
    websWrite(wp, pStr);
    websDone(wp);
    sleep(1);
sys_info_end: 
    if(sysInfo.title)
        free(sysInfo.title);
    if(sysInfo.text)
        free(sysInfo.text);

    free(pStr);
    cJSON_Delete(root);
    cJSON_Delete(data);

}


/*获取刀片信息*/
void getCardInfo(Webs *wp){

}

void getSensorInfo(Webs *wp){
    int         wRet;
    int         nSensors = 0;
    uint8_t     SensorNumber;
    char        SensorName[MAX_ID_STR_LEN];
    uint8_t     OwnerID;
    uint8_t     OwnerLUN;
    uint8_t     SensorType;
    uint8_t     SensorUnit1;
    uint8_t     SensorUnit2;
    uint8_t     SensorUnit3;
    int         SensorReading;
    uint8_t     RawReading;
    uint16_t    SensorState;
    uint8_t     DiscreteState;
    int         LowNRThresh;
    int         LowCTThresh;
    int         LowNCThresh;
    int         HighNCThresh;
    int         HighCTThresh;
    int         HighNRThresh;
    int         SensorAccessibleFlags;
    struct sensor_data *pSensorBuff = NULL;
    long int reading,lownr,lowct,lownc,highnc,highct,highnr = 0;
    unsigned char *pStartBuff = NULL;
    IPMI20_UDS_SESSION_T    UDSSession;

    //Create session
    wRet = LIBIPMI_CreateSession(&UDSSession, 10);
   
    /* Get number of SEL records in the system at this time */
    wRet = LIBIPMI_HL_GetSensorCount(&UDSSession,&nSensors,DEFAULT_TIMEOUT);
    if( wRet != 0 )
    {
        printf("Error getting num of sensors\n");
        goto error_out;
    }
    else
    {
        //printf("success getting num of sensors: %d\n",nSensors);  //this is all sensor count
        /* Now get all sensors records */
        if(!nSensors)
        {
            /* There are no sensors present at this time */
            goto error_out;
        }

        /* Allocate the buffer to hold sensors records */
        pSensorBuff = (struct sensor_data *) malloc(nSensors * sizeof(struct sensor_data));
        if(pSensorBuff == NULL)
        {
            printf("Error alloc memory!\n");
            goto error_out;
        }
        memset(pSensorBuff, 0, nSensors * sizeof(struct sensor_data));
        pStartBuff = (unsigned char *)pSensorBuff;

        printf("sensorcount = %d\n", nSensors);
        nSensors -= 1;  //remove first sdr
        wRet = LIBIPMI_HL_GetAllSensorReadings(&UDSSession,pSensorBuff, nSensors,DEFAULT_TIMEOUT);
        
        //Close session
        LIBIPMI_CloseSession(&UDSSession );

        if(wRet != 0)
        {
            printf("Error reading All Sensors\n");
            goto error_out;
        }
        else
        {

            // cchar *pStr;
            // int code = 200;
            // cJSON * root =  cJSON_CreateObject();
            // cJSON  *pJsonArry,*pJsonsub;
   
            // pJsonArry=cJSON_CreateArray();   /*创建数组*/
            

           
            logmsg(2, "-----------------------sensor----------------------");
           
           
          
            // cJSON_AddStringToObject(data, "buildTime", BuildTime);
            // cJSON_AddStringToObject(data, "fwVersion", FwVersion);
            //printf("sesscess reading All Sensors, nNumSensor = %d\n", nNumSensor);    //this is sensor number
            /* Write entries here */
            while(nSensors)
            {
                reading = pSensorBuff->sensor_reading * 1000;
                lownr = pSensorBuff->low_non_recov_thresh * 1000;
                lowct = pSensorBuff->low_crit_thresh * 1000;
                lownc = pSensorBuff->low_non_crit_thresh * 1000;
                highnc = pSensorBuff->high_non_crit_thresh * 1000;
                highct = pSensorBuff->high_crit_thresh * 1000;
                highnr = pSensorBuff->high_non_recov_thresh * 1000;

                //TODO: Lusa get sensor info here.
                // WEBPAGE_WRITE_JSON_RECORD(HL_GETALLSENSORS,
                //             pSensorBuff->sensor_num,
                //             pSensorBuff->sensor_name,
                //             pSensorBuff->owner_id,
                //             pSensorBuff->owner_lun,
                //             pSensorBuff->sensor_type,
                //             pSensorBuff->sensor_units[0],
                //             pSensorBuff->sensor_units[1],
                //             pSensorBuff->sensor_units[2],
                //             reading,
                //             pSensorBuff->raw_reading,
                //             pSensorBuff->sensor_state,
                //             pSensorBuff->discrete_state,
                //             lownr,
                //             lowct,
                //             lownc,
                //             highnc,
                //             highct,
                //             highnr,
                //             pSensorBuff->SensorAccessibleFlags);
                // cJSON_AddItemToArray(pJsonArry,pJsonsub=cJSON_CreateObject()); /* 给创建的数组增加对对象*/
                // cJSON_AddStringToObject(pJsonsub, "PROV_BRANCH_NO","000002");      /* 给对象增加内容 */                   
                // cJSON_AddStringToObject(pJsonsub, "SRC_SYS","UBPS");                                        
                // cJSON_AddStringToObject(pJsonsub, "CUST_OAC_BRANCH_NO","120101");                                                         
                // cJSON_AddStringToObject(pJsonsub, "ROLE","3");                 
                // cJSON_AddStringToObject(pJsonsub, "IPSN_NO","1");   

                pSensorBuff++;
                nSensors--;
            }

            // cJSON_AddItemToObject(root, "data", pJsonArry);//根节点下添加
            // cJSON_AddItemToObject(root, "msg", cJSON_CreateString(""));
            // cJSON_AddItemToObject(root, "code", cJSON_CreateString("200"));
            // pStr = cJSON_Print(pJsonArry);

            logmsg(2, "-----------------------sensor----------------------");

            // websSetStatus(wp, WEBS_KEEP_ALIVE);
            // websWriteHeaders(wp, -1, 0);
            // websWriteEndHeaders(wp); 
            // //websWrite(wp, "[");
            // websWrite(wp, pStr);
            // //websWrite(wp, "]");
            // //websFlush(wp, 0);
            // websDone(wp);
        }
    }

    

    //TODO: lusa








error_out:
    if(pStartBuff != NULL)
    {
        free(pStartBuff);
    }

    
}



void buy(Webs *wp)
{
    cchar    *name, *age;
    name = websGetVar(wp, "name", NULL);
    age = websGetVar(wp, "age", NULL);
     logmsg(2, "----------------------------11-----------------");
    logmsg(2, "name value is : %s", name );
     logmsg(2, "age value is : %s", age );
    websSetStatus(wp, 200);
    websWriteHeaders(wp, -1, 0);
    websWriteEndHeaders(wp);
   
    websWrite(wp, "Name %s", name);
    websWrite(wp, "age %s", age); 
    websFlush(wp, 0);
    websDone(wp);
}



// /*
//     Implement /action/actionTest. Parse the form variables: name, address and echo back.
//  */
void actionTest(Webs *wp)
{
    IPMI20_UDS_SESSION_T    UDSSession;
    GetDevIDRes_T   DeviceID;
    char BuildTime[30] = "2020-3-17";
    char FwVersion[10] = "5.555";
    char MacAddr[18] = "22.22.22.22.22.22";
    char IpAddr[16] = "192.168.255.255";

    //Create session
    printf("actionTest!\n");
    LIBIPMI_CreateSession(&UDSSession, 10);
    IPMICMD_GetDeviceID( &UDSSession, &DeviceID, DEFAULT_TIMEOUT);
    LIBIPMI_CloseSession(&UDSSession );

    char *pStr;

    char *testStr;
    testStr = malloc(500); 
    //sprintf(testStr, "{data: {\"Version\": \"%s\", \"MAC\": \"%s\", \"IP\": \"%s\"}, \"msg\":\"\"}", FwVersion, MacAddr, IpAddr);

    sprintf(testStr, "{\n\t\"data\": {\n\t\t\"buildTime\":\"%s\",\n\t\t\"fwVersion\":\"%s\",\n\t\t\"macAddr\":\"%s\",\n\t\t\"ipAddr\":\"%s\"\n\t},\n\t\"msg\":\"\",\n\t\"code\": %d\n}", \
        BuildTime, FwVersion, MacAddr, IpAddr, 200);


    //sprintf(testStr, "jimbo and lusa are very confused, please git me some tips, my god!");

    pStr = testStr;

    cJSON * root =  cJSON_CreateObject();
    cJSON * data =  cJSON_CreateObject();
    printf("log1\n");
    //cJSON_AddItemToObject(root, "data", data);//根节点下添加
    cJSON_AddStringToObject(root, "msg", NULL);
    cJSON_AddNumberToObject(root, "code", 200);
    cJSON_AddStringToObject(data, "buildTime", BuildTime);
    cJSON_AddStringToObject(data, "fwVersion", FwVersion);
    cJSON_AddStringToObject(data, "macAddr", MacAddr);
    cJSON_AddStringToObject(data, "ipAddr", IpAddr);
 //   /*pStr = */cJSON_Print(root);     //include malloc
    
    printf("%s\n", pStr);
    int i=0;
    while(pStr[i])
    {
        printf("%#x ", pStr[i++]);
    }
    printf("\n");
    websSetStatus(wp, 200);
    websWriteHeaders(wp, -1, 0);
    websWriteEndHeaders(wp);
    websWrite(wp,"%s", pStr);
    websFlush(wp, 0);
    websDone(wp);

    if(pStr)
        free(pStr);

    cJSON_Delete(root);
    cJSON_Delete(data);

    
}


