/*--------------------------------------------------------------------------*
 Project:
 File: gyro_Logger.h


*--------------------------------------------------------------------------*/
#ifndef __GYRO_LOGGER_H__
#define __GYRO_LOGGER_H__


#include <nn/types.h>
#include <nw/ut.h>

#include "sys.h"
#include "../seq/Config.h"
#include "../seq/ConfigDefine.h"
#include "../seq/TesterLog/ProductionLog.h"

namespace uji {
namespace eva {


namespace {
    const wchar_t wcUjiRootDir[]    = L"sdmc:/uji";
    const wchar_t wcGyroDirectory[] = L"sdmc:/uji/gyro";    // ジャイロ検査用のディレクトリ
    const char MyEOF = 0x1a;                                // EOF
}

// デバッガにNN_LOG出力する場合は有効に
// #define DEBUG_LOGGER_NN_LOG
/*
    外部デバイスにログを残す為のクラス
*/
class GyroLogger
{
public:
    GyroLogger() : m_IsInitialized(false), m_Buffer(0) {}
    virtual ~GyroLogger() {}

    typedef enum SDLOGWriteType
    {
        SDLOG_WRITE_TYPE_OVERWRITE   = 0,   // 同名ファイルが存在していたら、上書き
        SDLOG_WRITE_TYPE_CONTINUANCE        // 同名ファイルが存在していたら、追記書込み
    }
    SDLOGWriteType;

    /*
        Desc: SDカード検出
    */
    bool IsSdmcInserted()
    {
#ifdef EVA_GYRO_C
            return false;
#else

#if (!defined(EVA_GYRO_M) && !defined(EVA_GYRO_C))
        // LINE設定の場合のみ、SDカードを認識可能とします
        // GyroMの場合は検査器搭載のCTRに保存するため、SDカードが存在すればログを残します
        if (seq::Config().Get().TestMode == seq::pl::LINE)
        {
#endif
            if (nn::fs::IsSdmcInserted())
            {
                return true;
            }
#if (!defined(EVA_GYRO_M) && !defined(EVA_GYRO_C))
        }
#endif
        return false;
#endif // EVA_GYRO_C
    }

    /*
        Desc: ファイルオープン

        Args: fileName   - セーブするファイル名（ディレクトリは固定なので指定不要）
              bufferSize - Flushで実際に書き込むまでに保持するためのバッファサイズ
              type       - 上書きor追記

        Rtns: true/false
    */
    bool OpenFile(const wchar_t* fileName, u32 bufferSize, SDLOGWriteType type=SDLOG_WRITE_TYPE_CONTINUANCE)
    {
        wchar_t tmpPath[256];

        if (m_IsInitialized)
        {
            // 既にオープン済み
            return false;
        }

        std::wcscpy(tmpPath, wcGyroDirectory);
        std::wcscat(tmpPath, L"/");
        std::wcscat(tmpPath, fileName);
        nn::Result result = m_FileStream.TryInitialize(
            tmpPath,
            (nn::fs::OPEN_MODE_WRITE | nn::fs::OPEN_MODE_READ | nn::fs::OPEN_MODE_CREATE)
        );
        if (result.IsFailure())
        {
            return false;
        }

        s64 size = m_FileStream.GetSize();
#ifdef DEBUG_LOGGER_NN_LOG
        NN_LOG("file_size(%lld) buf_size(%d)\n", size, bufferSize);
#endif
        if ((size != 0) && (type == SDLOG_WRITE_TYPE_CONTINUANCE))
        {
             m_FileStream.Seek(0, nn::fs::POSITION_BASE_END);
        }

        m_Buffer = static_cast<char*>(sys::Alloc(m_BufferSize = bufferSize));
        std::memset(m_Buffer, '\0', bufferSize);
        m_CurrentBufPtr = m_Buffer;

        m_IsInitialized = true;
        return true;
    }

    /*
        Desc: ファイルクローズ
    */
    void CloseFile()
    {
        if (!m_IsInitialized)
        {
            return;
        }

        m_FileStream.Finalize();

        sys::Free(m_Buffer);
        m_IsInitialized = false;
    }

    /*
        Desc: ディレクトリ生成
    */
    bool CreateDirectory()
    {
        nn::fs::TryCreateDirectory(wcUjiRootDir);
        nn::Result result = nn::fs::TryCreateDirectory(wcGyroDirectory);
        if (result.IsFailure())
        {
            return false;
        }
        return true;
    }

    /*
        Desc: ファイルサイズの取得
    */
    s64 GetFileSize() { return m_FileStream.GetSize(); }

    // バッファに追記
    bool Printf(const char *fmt, ...);
    // SDに保存
    void Flush(void);

private:
    nn::fs::FileStream m_FileStream;
    bool m_IsInitialized;
    char* m_Buffer;
    char* m_CurrentBufPtr;
    u32 m_BufferSize;

    bool VPrintf(const char* format, std::va_list vlist);
    bool PutString(const char *str);
    bool Write(const void* buf, u32 size);
};


} // namespace
}

#endif
