#include "file.h"
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>



//读取文件到内存  用完需释放
int ReadTxtFile(const char *pFileName, char **pMessage)
{
    FILE *stream = fopen(pFileName, "r");
    if (stream == NULL)
    {
        //LOG("ReadFile %s err!!!",pFileName);
        return -1;
    }

    fseek(stream, 0L, SEEK_END);
    int iLen = ftell(stream);
    fseek(stream, 0L, SEEK_SET);

    char *pFileBuff = (char *)calloc(1,iLen + 1);
    fread(pFileBuff, iLen, 1, stream);
    fclose(stream);
    *pMessage = pFileBuff;
    return iLen;
}

//写入内存到文件
int WriteTxtFile(const char *pFileName, char **pMessage)
{
    if (pMessage == NULL || *pMessage == NULL)
    {
        printf("WriteFile %s pMessage err!!!",pFileName);
        return -1;
    }

    FILE *stream = fopen(pFileName, "w");
    if (stream == NULL)
    {
        printf("WriteFile %s err!!!",pFileName);
        return -2;
    }

    int iLen = fwrite(*pMessage, 1, strlen(*pMessage), stream);
	fflush(stream);
    fclose(stream);
    return iLen;
}


cJSON *readJsonFromFile(char *fileName)
{
    if (!fileName)
    {
        return NULL;
    }
    char * pConfig = NULL;
    cJSON *pCfgJsRoot = NULL;
    ReadTxtFile(fileName,&pConfig);
    if (!pConfig)
    {
        return NULL;
    }
    pCfgJsRoot = cJSON_Parse(pConfig);
    if(pConfig) 
        free(pConfig);
    return pCfgJsRoot;
}

int saveJsonToFile(char *fileName,cJSON *pjRoot)
{
    int len = 0;
    if (fileName == NULL || pjRoot == NULL)
    {
        printf("input parameters error...\n");
        return 0;
    }
    char *msg = cJSON_Print(pjRoot);
    if (msg )
    {
        len = WriteTxtFile(fileName,&msg);
        free(msg);
        msg = NULL;
    }
    return len;
}


int WriteHexFile(const char *pFileName, unsigned char *pData, int len)
{
    unsigned int ret = 0;
    if (pFileName == NULL || pData == NULL || len < 1)
    {
        //LOG("WriteHexFile %s pMessage err!!!",pFileName);
        return -1;
    }

    FILE *stream = fopen(pFileName, "wb");
    if (stream == NULL)
    {
        //LOG("WriteHexFile %s err!!!",pFileName);
        return -2;
    }

    ret = fwrite(pData, sizeof(char), len, stream);
	fflush(stream);
    fclose(stream);
    return ret;
}

int ReadHexFile(const char *pFileName, unsigned char **pData)
{
    FILE *stream = fopen(pFileName, "rb");
    if (stream == NULL)
    {
        printf("ReadFile %s err!!!",pFileName);
        return -1;
    }

    fseek(stream, 0L, SEEK_END);
    int iLen = ftell(stream);
    fseek(stream, 0L, SEEK_SET);

    unsigned char *pFileBuff = (unsigned char *)calloc(1,iLen);
    fread(pFileBuff, sizeof(char), iLen, stream);
    fclose(stream);
    *pData = pFileBuff;
    return iLen;
}

int ReadHexFileAddLen(const char *pFileName, unsigned char **pData)
{
    FILE *stream = fopen(pFileName, "rb");
    if (stream == NULL)
    {
        //LOG("ReadFile %s err!!!",pFileName);
        return -1;
    }

    fseek(stream, 0L, SEEK_END);
    int iLen = ftell(stream);
    fseek(stream, 0L, SEEK_SET);

    unsigned char *pFileBuff = (unsigned char *)calloc(1,iLen+4);
    unsigned int *len = (unsigned int *)pFileBuff;
    *len = iLen;
    fread(pFileBuff+4, 1, iLen, stream);
    fclose(stream);
    *pData = pFileBuff;
    return iLen;
}

//创建多级目录
int createMultiLevelDir(char* sPathName)  
{  
    char DirName[256];      
    int i, len;
    
    strcpy(DirName, sPathName);      
    len = strlen(DirName);             
    if('/' != DirName[len-1]) {  
        strcat(DirName, "/");
        len++;
    }           
            
    for(i=1; i<len; i++)      
    {      
        if('/' == DirName[i])      
        {      
            DirName[i] = '\0';      
            if(access(DirName, F_OK) != 0)      
            {      
                if(mkdir(DirName, 0777) == -1)      
                {       
                    perror("mkdir() failed!");       
                    return 0;       
                }      
            }    
            DirName[i] = '/';      
        }      
    }    
          
    return 1;      
} 

int int2Byte(int val,unsigned char *bytes)
{
    bytes[0] = (unsigned char)  (0x000000ff & val);
    bytes[1] = (unsigned char) ((0x0000ff00 & val) >> 8);
    bytes[2] = (unsigned char) ((0x00ff0000 & val) >> 16);
    bytes[3] = (unsigned char) ((0xff000000 & val) >> 24);
    return 1;
}

//转换成Comtrad 格式文件 文件名  通道数量 1 or 4 
int toComtradeFile(char* sFileName,char* destFileName,int ch,int headLen)
{
    unsigned char *pAreaS = NULL;
    unsigned char *pArea = NULL;
    int fileLen = ReadHexFile(sFileName, &pAreaS);
    if(fileLen<0)
        return 0;
    if(headLen > 0)
    {
        pArea = pAreaS + headLen;
        fileLen -= headLen;
    }
    else pArea = pAreaS;

    if(fileLen%ch!=0)
        return 0;
    int chLen = fileLen/ch/2;
    int i = 0;
    unsigned char tempBuf[4] = {0};

    FILE *stream = fopen(destFileName, "wb");
    if (stream == NULL)
        return 0;

    for(i = 0;i < chLen;i ++)
    {
        int2Byte(i,tempBuf);
        fwrite(tempBuf, 4, 1, stream);
        int2Byte(i*1000,tempBuf);
        fwrite(tempBuf, 4, 1, stream);

        if(ch == 1)
        {
            fwrite(pArea + i*2, 2, 1, stream);
        }
        else if(ch == 4)
        {
            fwrite(pArea + i*8, 8, 1, stream);
        }
        else if(ch == 8)
        {
            fwrite(pArea + i*16, 16, 1, stream);
        }
    }
	fflush(stream);
    fclose(stream);
    free(pAreaS);
    return 1;
}

#if 0
//转换成CSV 格式文件 文件名  通道数量1 or 4 
int toCsvFile(char* sFileName,char* destFileName,int ch,int headLen)
{
    unsigned char *pAreaS = NULL;
    unsigned char *pArea = NULL;
    int fileLen = ReadHexFile(sFileName, &pAreaS);
    if(headLen > 0)
    {
        pArea = pAreaS + headLen;
        fileLen -= headLen;
    }
    else pArea = pAreaS;

    if(fileLen<0)
        return 0;
    if(fileLen%ch!=0)
        return 0;
    int chLen = fileLen/ch/2;
    
    int i = 0;
    unsigned char tempBuf[4] = {0};
    FILE *stream = fopen(destFileName, "w");
    if (stream == NULL)
        return 0;

    char buf[256] = {0};
    
    for(i = 0;i < chLen;i ++)
    {
        if(ch == 4)
        {
            I16X4_t *pVal = pArea + 8*i;
            sprintf(buf,"%d,%d,%d,%d\n",pVal->val1,pVal->val2,pVal->val3,pVal->val4);
            fwrite(buf,strlen(buf),1,stream);
        }
        else if(ch == 8)
        {
            I16X8_t *pVal = pArea + 16*i;
            sprintf(buf,"%d,%d,%d,%d,%d,%d,%d,%d\n",pVal->val[0],pVal->val[1],pVal->val[2],pVal->val[3],
                pVal->val[4],pVal->val[5],pVal->val[6],pVal->val[7]);
            fwrite(buf,strlen(buf),1,stream);
        }
        else if(ch == 1)
        {
            unsigned char *p = pArea + chLen*0 + 2*i;
            short v1 = (*p)&0xff | (((*(p+1))&0xff)<<8);
            sprintf(buf,"%d\n",v1);
            fwrite(buf,strlen(buf),1,stream);
        }
    }
    fclose(stream);
    free(pAreaS);
    return 1;
}
#endif

long tell(const char* pFileName)
{
	long fileSize = -1;
	do
	{
		FILE* fp;
		fp = fopen(pFileName, "rb");
		if (fp == NULL)
			break;

		fseek(fp, 0L, SEEK_END);
		fileSize = ftell(fp);
		fclose(fp);
	}while (0);

	return fileSize;
}

int findWaveFile(char *dir,unsigned int fileIndex,char *fileName)
{
    struct dirent **namelist;
    int index=0;
    int n = scandir(dir,&namelist,0,alphasort);
    char indexBuf[128] = {0};
    sprintf(indexBuf,"%08x_",fileIndex);

    printf("findWaveFile in %s, fileIndex:%x indexBuf:%s",dir,fileIndex,indexBuf);
    while(index < n )//删除1/4
    {
        if (strcmp(namelist[index]->d_name,".") == 0 || strcmp(namelist[index]->d_name,"..") == 0)
        {
            index ++;
            continue;
        }
        if (NULL != strstr(namelist[index]->d_name,indexBuf))
        {
            sprintf(fileName,"%s/%s",dir,namelist[index]->d_name);
            return 1;
        }
        index++;
    }
    //printf("%s 文件数量 %d  _index:%d\r\n",dir,n,index);
    return 0;
}




