/*--------------------------------------------------------------------------*
  Project: CTR_TRIAL
  File:    InspectLog_Viewer.cpp

  Copyright 2010 Nintendo.  All rights reserved.

  These coded instructions, statements, and computer programs contain
  proprietary information of Nintendo of America Inc. and/or Nintendo
  Company Ltd., and are protected by Federal copyright law.  They may
  not be disclosed to third parties or copied or duplicated in any form,
  in whole or in part, without the prior written consent of Nintendo.

*--------------------------------------------------------------------------*/
#include "InspectLog_Viewer.h"
#include "InspectLog.h"
#include "sys_App.h"

#include <nn.h>
#include <nn/fnd.h>
#include <nn/gx.h>
#include <stdlib.h>
#include <nw/types.h>
#include <stdio.h>
#include <string>

using namespace uji::seq;
using namespace std;

namespace uji {
namespace seq {

void Run_InspectLog_Viewer()
{
    InspectLog_Viewer * ilv = new InspectLog_Viewer;
    ilv->Initialize();
    ilv->Run();
    delete ilv;
}

//============================================================================
//
// InspectLog_Viewer
//
//============================================================================
/*---------------------------------------------------------------------------
 初期化
---------------------------------------------------------------------------*/
void InspectLog_Viewer::Initialize()
{
    // 上LCD用
    (void)m_WindowManager.CreateWindow(&m_UpperWindow,       NN_GX_DISPLAY0, 0, 0);
    m_UpperWindow.SetTitle("INSPECT LOG VIEWER ");

    // マスター透過度を変更します
    m_WindowManager.SetAlpha(255);
}

/*---------------------------------------------------------------------------
ログ描画
---------------------------------------------------------------------------*/
void InspectLog_Viewer::DrawLog(int row, char * key, char * value)
{
    m_UpperWindow.SetTextColor(sys::ATTR_COLOR_WHITE);

    // 描画開始位置
    m_UpperWindow.Gotoxy(0, row);
    m_UpperWindow.Printf("%-10s %s",key,value);

}

/*---------------------------------------------------------------------------
エラーメッセージ描画
---------------------------------------------------------------------------*/
void InspectLog_Viewer::DrawErrorMessage(sys::GraphicsDrawing* gfx,LogResult lr)
{
    gfx->m_DrawFramework->SetRenderTarget(NN_GX_DISPLAY0);
    gfx->m_DrawFramework->Clear();
    m_WindowManager.DrawDisplay0();

    LogResultCode lrc;

    if ( lr < 0 )
    {
        // エラーの場合
        m_UpperWindow.SetTextColor(sys::ATTR_COLOR_YELLOW);
        m_UpperWindow.Gotoxy(0, 0);
        m_UpperWindow.Printf( "-------------------------------------------------------\n");
        m_UpperWindow.Gotoxy(0, 1);
        m_UpperWindow.Printf( "   Error occurred (%s)!\n",lrc.ToString(lr).c_str());
        m_UpperWindow.Gotoxy(0, 2);
        m_UpperWindow.Printf( "-------------------------------------------------------\n");
    }
    else
    {
        // エラーではない場合(NO_LOG_ENTRYとか)
        m_UpperWindow.SetTextColor(sys::ATTR_COLOR_WHITE);
        m_UpperWindow.Gotoxy(0, 0);
        m_UpperWindow.Printf( "-------------------------------------------------------\n");
        m_UpperWindow.Gotoxy(0, 1);
        m_UpperWindow.Printf( "  %s \n",lrc.ToString(lr).c_str());
        m_UpperWindow.Gotoxy(0, 2);
        m_UpperWindow.Printf( "-------------------------------------------------------\n");
    }

    // ファイル、ハッシュ情報のダンプ (注意 ファイルが開けないとGet_Hash_ByFileとかは止まる可能性が高い）
    if ( (lr == LogResultCode::HASH_MISMATCH ) ||
         (lr == LogResultCode::HASH_ALL_FF )   ||
         (lr == LogResultCode::NO_LOG_ENTRY))
    {

        m_UpperWindow.SetTextColor(sys::ATTR_COLOR_WHITE);

        m_UpperWindow.Printf( "fileSize:%lld\n\n",    m_InspectLog.Get_FileSize());

        m_UpperWindow.Printf( "HashEntryValue :%s\n", (m_InspectLog.Get_HashEntryValue()).c_str());
        m_UpperWindow.Printf( "FileHash       :%s\n", (m_InspectLog.Get_FileHash()).c_str());
        m_UpperWindow.Printf( "DataHash       :%s\n", (m_InspectLog.Get_DataHash()).c_str());
    }

    gfx->m_DrawFramework->SwapBuffers();
}


/*---------------------------------------------------------------------------
 エラーメッセージ表示処理
---------------------------------------------------------------------------*/
void InspectLog_Viewer::RunErrorMessage(sys::GraphicsDrawing* gfx,LogResult lr)
{
    DEBUG_WRITE("InspectLog_Viewer::RunErrorMessage error(%d).\n",lr);

    do
    {
        // パッド入力処理
        sys::Pad().UpdatePad();

        // ウインドウ処理
        m_WindowManager.UpdatePad(sys::Pad());  // パッド処理
        m_WindowManager.Update();               // 更新処理

        // 上LCDにエラーメッセージを描画
        DrawErrorMessage(gfx,lr);

        // Vsyncを待つ
        gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);

        // restore gl state ※RenderSystemの文字描画実行の際は必ず戻すこと
        for (int attrindex = 0; attrindex < 12; attrindex++)
            glDisableVertexAttribArray(attrindex);

    } while (!sys::Pad().IsButtonDown(sys::Pad::BUTTON_B));

    // ウインドウ破棄
    m_WindowManager.DestroyWindow(&m_UpperWindow);
}

/*---------------------------------------------------------------------------
 上画面描画処理
---------------------------------------------------------------------------*/
int InspectLog_Viewer::DrawUpperLCD(sys::GraphicsDrawing* gfx, int display_log_entry_num)
{
    gfx->m_DrawFramework->SetRenderTarget(NN_GX_DISPLAY0);
    gfx->m_DrawFramework->Clear();
    m_WindowManager.DrawDisplay0();


    m_UpperWindow.SetTextColor(sys::ATTR_COLOR_WHITE);
    m_UpperWindow.Gotoxy(0, 1);
    m_UpperWindow.Printf( " DeviceIdHash   :%s\n", m_InspectLog.Get_DeviceIdHash().c_str());

    m_UpperWindow.Gotoxy(0, 2);
    m_UpperWindow.Printf( " RfuMacAddress  :%s\n", m_InspectLog.Get_RfuMacAddress().c_str());

    m_UpperWindow.Gotoxy(0, 3);
    m_UpperWindow.Printf( " SerialNumber   :%s\n", m_InspectLog.Get_SerialNumber().c_str());

    m_UpperWindow.Gotoxy(0, 4);
    m_UpperWindow.Printf( " RegionCode     :%s\n", m_InspectLog.Get_RegionCode().c_str());

    m_UpperWindow.Gotoxy(0, 5);
    m_UpperWindow.Printf( " BondingOption  :%s\n", m_InspectLog.Get_BondingOption().c_str());

    m_UpperWindow.Gotoxy(0, 6);
    m_UpperWindow.Printf( " Comment        :%s\n", m_InspectLog.Get_Comment().c_str());

    m_UpperWindow.Gotoxy(0, 7);
    m_UpperWindow.Printf( " CommentUpdated :%s\n", m_InspectLog.Get_CommentUpdated().c_str());


    // 文字描画
    gfx->SetScreenSize(gfx->DISPLAY0_WIDTH, gfx->DISPLAY0_HEIGHT);

    gfx->m_DrawFramework->SwapBuffers();

    return display_log_entry_num;
}

/*---------------------------------------------------------------------------
 実行部
---------------------------------------------------------------------------*/
void InspectLog_Viewer::Run()
{
    sys::GraphicsDrawing* gfx = sys::GraphicsDrawing::GetInstance();

    LogResult lr;
    lr = m_InspectLog.Initialize();
    if (( lr != LogResultCode::SUCCESS )  &&
        ( lr != LogResultCode::HASH_MISMATCH ))
    {
        RunErrorMessage(gfx,lr); //エラー時の処理を行う
        return;
    }


    int displayLogEntryNum = 0;
    do
    {
        // パッド入力処理
        sys::Pad().UpdatePad();

        // ウインドウ処理
        m_WindowManager.UpdatePad(sys::Pad());// パッド処理
        m_WindowManager.Update();             // 更新処理

        if (sys::Pad().IsButtonDown(sys::Pad::BUTTON_X))
        {
            m_InspectLog.Create_DataStructure();
        }

        if (sys::Pad().IsButtonDown(sys::Pad::BUTTON_Y))
        {
            m_InspectLog.Set_Comment("ABCTV", "2010/12/04");
        }

        // 上LCDの描画
        displayLogEntryNum = DrawUpperLCD(gfx,displayLogEntryNum);

        // Vsyncを待つ
        gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);

    } while (!sys::Pad().IsButtonDown(sys::Pad::BUTTON_B));


    // ウインドウ破棄
    m_WindowManager.DestroyWindow(&m_UpperWindow);
}

}   // usingnamespace seq
}   // usingnamespace uji
