#include "common/posix/FInStream.h"

#if defined(ANDROID)
#include <android/log.h>
#define printf(...) __android_log_print(ANDROID_LOG_DEBUG, "FInStream", __VA_ARGS__);
#endif

using namespace NS_DM_Client::NS_Common;


FInStream::FInStream() : m_finished(false), m_file(0)
{}

bool FInStream::Open(const char* fileName)
{
    m_file = fopen(fileName, "r");
    if (!m_file)
    {
        printf("ERROR: Cannot open logfile \"%s\"", fileName);
        return false;
    }
    m_finished = false;
    printf("Configuration file is = %s", fileName);
    return true;
}


bool FInStream::Open(String &fileName)
{
    return Open(fileName.c_str());
}


void FInStream::Close()
{
    if(m_file != NULL) fclose(m_file);
}


bool FInStream::GetLine(String& line)
{
    if (!m_file || m_finished)
        return false;

    int c;
    do {
        c = fgetc(m_file);
        if (c != '\r' && c != '\n' && c != EOF)
            line += (char)c;
        else
            break;
    }
    while (c != EOF);

    if(c == EOF) m_finished = true;
    else m_finished = false;

    if (!m_finished) {
        c = fgetc(m_file);
        if (c != '\r' && c != '\n') {
            ungetc(c, m_file);
        }
    }

    return true;
}
