#include "Utils.h"
#include "common/android/FOutStream.h"
#include <stdio.h>
#include <stdarg.h>
#include <errno.h>

#include <time.h>
#include <sys/types.h>
#include <sys/timeb.h>

#include "platform.h"

#include <sys/time.h>
#include <android/log.h>
#define printf(...) __android_log_print(ANDROID_LOG_DEBUG, "FOutStream", __VA_ARGS__);


using namespace NS_DM_Client::NS_Common;

    FOutStream::FOutStream(): m_file(0)
    {
    }
    //-------------------------------------------------------------------------------------------

    FOutStream::~FOutStream()
    {
    }
    //-------------------------------------------------------------------------------------------

    void FOutStream::Open(const char* filename)
    {
        FILE* fp = fopen(filename, "a");
        if (fp == NULL)
        {
            printf("ERROR: Cannot create logfile %s by %s", filename, strerror(errno));
            return;
        }
        m_file = fp;
    }
    //-------------------------------------------------------------------------------------------

    void FOutStream::Close()
    {
        if(m_file != NULL)
        {
            fclose(m_file);
        }
    }
    //-------------------------------------------------------------------------------------------

    void FOutStream::Write(const char* buffer, int size)
    {
        if (!m_file)
        {
            printf("WARNING: No logfile");
            return;
        }
        size_t count = fwrite(buffer, 1, size, m_file);
        if ((int)count < size)
        {
            printf("WARNING: Failed to write all message to file");
        }
        int res = fflush(m_file);
        if (res != 0)
        {
            printf("WARNING: Failed to flush file's buffer");
        }
    }
    //-------------------------------------------------------------------------------------------

    int FOutStream::FormatMessage(char* buffer, int size, int threadID, const char* loggerName, 
        const char* category, const char* functionName)
    {
        struct timeval start;
        memset(&start, 0, sizeof(start));
        gettimeofday(&start, NULL);
        struct tm * ptm = localtime(&start.tv_sec);
        int written = snprintf(buffer, size, "%02d:%02d:%02d.%03u %5u %s %s %s", ptm->tm_hour, ptm->tm_min, ptm->tm_sec, start.tv_usec/1000, threadID, loggerName, functionName, category);

        return written;
    }
    //-------------------------------------------------------------------------------------------

    int FOutStream::FormatMessage(char* buffer, int size, int threadID, const char* loggerName, const char* category)
    {
        struct timeval start;
        memset(&start, 0, sizeof(start));
        gettimeofday(&start, NULL);
        struct tm * ptm = localtime(&start.tv_sec);
        int written = snprintf(buffer, size, "%02d:%02d:%02d.%03u %5u %s %s", ptm->tm_hour, ptm->tm_min, ptm->tm_sec, start.tv_usec/1000, threadID, loggerName, category);

        return written;
    }
