#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include "debug_print.h"

//standard: iso-8601
void debug_get_time(char *buffer, int len)
{
	struct timeval tv;
	struct tm *result;
	time_t timep;
	suseconds_t millitm;
#if 1
	gettimeofday(&tv, NULL);
	timep = tv.tv_sec;
    	millitm = (tv.tv_usec + 500) / 1000;
    	if (millitm == 1000) {
            ++timep;
            millitm = 0;
    	}
#endif
        //time(&timep);
	result = localtime(&timep);
	if (result != NULL) {
		if(buffer) {
			//snprintf(buffer, len, "%d-%02d-%02d %02d:%02d:%02d.%03d",
			//	 result->tm_year + 1900, result->tm_mon + 1, result->tm_mday,
			//	 result->tm_hour, result->tm_min, result->tm_sec, (int)millitm);
			snprintf(buffer, len, "%02d-%02d %02d:%02d:%02d.%03d",
				 result->tm_mon + 1, result->tm_mday,
				 result->tm_hour, result->tm_min, result->tm_sec, (int)millitm);
		}
	}
}

void getDayStr(char *buffer,int len){
    time_t timep;
    struct tm *p;
    time (&timep);
    p=localtime(&timep);
    strftime (buffer,len,"%Y-%m-%d",p);
}

#if 1
/*
 * demo:
* #define PRINT_FUNC   debug_print 
 */
int debug_print(const char *__restrict format, ...)
{
	va_list	valist;
	char buffer[512] = "";
	int ret;
	
	va_start(valist, format);
	ret = vsnprintf(buffer, sizeof(buffer), format, valist);
	va_end(valist);
	
	printf("%s", buffer);
        char opTime[16]={0};
        char logFileName[32]={0};
        getDayStr(opTime,16);
        sprintf(logFileName,"Log.%s",opTime);
        buffer_to_file(logFileName,buffer,strlen(buffer),"a");
	return ret;
}
#endif
int buffer_to_file(const char *pathname, const char *data, unsigned int size,const char *mod){
    FILE *fp = NULL;
    int temp = 0;
    //LOG_I("path:%s,data:%s,size:%d\n",pathname,data,size);
    fp = fopen(pathname, mod);
    if(fp==NULL){
        //LOG_I("open %s error\n", pathname);
            temp = -1;
    }else{
        fwrite(data, 1, size, fp);
        fclose(fp);
    }
    return temp;
}
