/**************************************************************************

コンフィグレーション設定

 *************************************************************************/
#include <string.h>
#include <nn.h>
#include <nn/fs.h>
#include "../sys/sys.h"
#include "../sys/sys_ClassMenu.h"
#include "../sys/sys_ShowMessage.h"
#include "../seq/CalcCrc.h"
#include "SaveDataConst.h"
#include "Config.h"

using namespace uji::sys;
using namespace uji::seq;

static int  GetListSize( const char **List );

Config::Member Config::m_StaticConfig;
Config::MemberAlt Config::m_StaticConfigAlt;


//コンフィグメニュー情報のインクルード
#define CONFIG_MENU_DEF
#include "./ConfigDefine.h"
#undef  CONFIG_MENU_DEF

const char ID_STRING[]="%02d-%02d ";
const char PREFIX_STRING[]="%-30s";
const char SUFFIX_STRING[]="%-10s\n";


const char PATH_NAME[]= UJI_SAVEARCHIVE "/uji";
const char FILE_NAME[]= UJI_SAVEARCHIVE "/uji/config.sav";



const char SIGNATURE[]="SEQ CONFIG" __DATE__ " " __TIME__ ;

struct SaveFormat
{
	char Signature[0x40];			//シグネチャ領域
	Config::Member Member;			//保存するデータ
	Config::MemberAlt MemberAlt;	//保存するデータもう一つ
	u16 CheckSum;					//チェックサム
};


/************************************************************************

Config

************************************************************************/

/************************************************************************
  パラメータの初期化
  ************************************************************************/
void Config::Initialize( void )
{
    int id = 0;
	while( m_ConfigInformation[id].Prefix[0] != '@' | m_ConfigInformation[id].Prefix[1] != '@'  )
    { 
		if( m_ConfigInformation[id].Prefix[0] != '@' )
        {
			//ページ先頭以外ならデータをデフォールトに変更
			*(m_ConfigInformation[id].Data) = m_ConfigInformation[id].DefaultData;
		}
		id++;
	}
}

/************************************************************************
  セーブ（アーカイブ別に振り分け）
  ************************************************************************/
bool Config::Save( void )
{
	if( strcmp( "sdmc:", UJI_SAVEARCHIVE )==0 )
	{
		return SaveToSd();
	}
	else if( strcmp( "data:", UJI_SAVEARCHIVE )==0 )
	{
		return SaveToCard();
	}
	else
	{
		SYS_PANIC("ILLEGAL ARCHIVE NAME" );
		return false;
	}
}

/************************************************************************
  セーブ（共通部分）
  ************************************************************************/
bool Config::SaveCommon( nn::fs::FileStream *file )
{

	SaveFormat *format = new SaveFormat;
	u16 readSum;
	u16 calcSum;
	nn::Result result;
	bool retValue;

	//セーブ用データ構造作成
	strcpy( format->Signature, SIGNATURE );
	format->Member		= m_StaticConfig;
	format->MemberAlt	= m_StaticConfigAlt;
	format->CheckSum	= 0;
	format->CheckSum	= CalcCheckSum( reinterpret_cast<u8 *>(format), sizeof(SaveFormat) );



	//セーブ
	file->Seek( 0, nn::fs::POSITION_BASE_BEGIN );
	if( file->Write( format, sizeof(SaveFormat) ) != sizeof( SaveFormat ) )
	{
		retValue=false;
		goto FINALLY;
	}

	//ベリファイ
	file->Seek( 0, nn::fs::POSITION_BASE_BEGIN );
	if( file->Read( format, sizeof(SaveFormat) ) != sizeof( SaveFormat ) )
	{
		retValue=false;
		goto FINALLY;
	}

	//チェックサム演算
	readSum = format->CheckSum;
	format->CheckSum=0;
	calcSum = CalcCheckSum( reinterpret_cast<u8 *>(format), sizeof(SaveFormat) );
	if( readSum != calcSum )
	{
		retValue=false;
		goto FINALLY;

	}

	//ここまできたら成功
	retValue=true;

FINALLY:
	delete format;
	return retValue;
}



/************************************************************************
  ＳＤカードへセーブ
  ************************************************************************/
bool Config::SaveToSd( void )
{
	nn::fs::FileStream file;
	nn::Result result;
	bool retValue;

	if( !nn::fs::IsSdmcInserted() ) return false;
	if( nn::fs::MountSdmc().IsFailure() ) return false;

	nn::fs::TryCreateDirectory( PATH_NAME );	//失敗しても無視
	result = file.TryInitialize( FILE_NAME,		nn::fs::OPEN_MODE_READ   | 
                                                nn::fs::OPEN_MODE_WRITE  | 
                                                nn::fs::OPEN_MODE_CREATE );
	if( result.IsSuccess()  )
	{
		retValue = SaveCommon( &file );
		file.Finalize();
	}else{
		retValue =  false;
	}

	nn::fs::Unmount("sdmc:");
	return retValue;
}

/************************************************************************
  ＣＴＲカードへセーブ
  ************************************************************************/
bool Config::SaveToCard( void )
{
	nn::fs::FileStream file;
	nn::Result result;
	bool retValue;

	//マウント
	result = nn::fs::MountSaveData();    
    if (result.IsFailure())
    {
	    if( result <= nn::fs::ResultNotFormatted()  ||
            result <= nn::fs::ResultBadFormat()     ||
            result <= nn::fs::ResultVerificationFailed() )
	    {
		    result = nn::fs::FormatSaveData( SAVE_DATA_MAX_FILES, SAVE_DATA_MAX_DIRECTORIES );
		    if( result.IsFailure()  ) return false;
		    result = nn::fs::MountSaveData();
		    if( result.IsFailure()  ) return false;
	    }
        else
        {
            return false;
        }
    }

	//オープン
	nn::fs::TryCreateDirectory( PATH_NAME );	//失敗しても無視
	result = file.TryInitialize( FILE_NAME,		nn::fs::OPEN_MODE_READ   | 
                                                nn::fs::OPEN_MODE_WRITE  | 
                                                nn::fs::OPEN_MODE_CREATE );
	if( result.IsSuccess()  )
	{
		retValue = SaveCommon( &file );
		file.Finalize();
	}else{
		retValue = false;
	}

	nn::fs::CommitSaveData();
	nn::fs::Unmount( "data:" );
	return retValue;
}



/************************************************************************
  ロード（アーカイブ別に振り分け）
  ************************************************************************/
bool Config::Load( void )
{
	if( strcmp( "sdmc:", UJI_SAVEARCHIVE )==0 )
	{
		return LoadFromSd();
	}
	else if( strcmp( "data:", UJI_SAVEARCHIVE )==0 )
	{
		return LoadFromCard();
	}
	else
	{
		SYS_PANIC("ILLEGAL ARCHIVE NAME" );
		return false;
	}
}

/************************************************************************
  ロード（共通部分）
  ************************************************************************/
bool Config::LoadCommon( nn::fs::FileInputStream *ifile )
{
	SaveFormat *format = new SaveFormat;
	u16 readSum;
	u16 calcSum;

	//ベリファイ
	if( ifile->Read( format, sizeof(SaveFormat) ) != sizeof( SaveFormat ) ) goto ERROR;

	//チェックサム演算
	readSum = format->CheckSum;
	format->CheckSum=0;
	calcSum = CalcCheckSum( reinterpret_cast<u8 *>(format), sizeof(SaveFormat) );
	if( readSum != calcSum ) goto ERROR;

	//シグネチャ照合
	if( strcmp( SIGNATURE, format->Signature )!=0 ) goto ERROR;

	//ここまでくればデータは妥当と判断されている。
	m_StaticConfig = format->Member;
	m_StaticConfigAlt = format->MemberAlt;

	delete format;
	return true;

ERROR:
	delete format;
	return false;
}

/************************************************************************
  ＳＤカードからロード
  ************************************************************************/
bool Config::LoadFromSd( void )
{
	nn::fs::FileInputStream ifile;
	bool retValue;

	if( !nn::fs::IsSdmcInserted() ) return false;
	if( nn::fs::MountSdmc().IsFailure() ) return false;


	if( ifile.TryInitialize( FILE_NAME ).IsSuccess() )
	{
		retValue = LoadCommon( &ifile );
		ifile.Finalize();
	}else{
		retValue = false;
	}
	nn::fs::Unmount("sdmc:");
	return retValue;
}

/************************************************************************
  ＣＴＲカードからロード
  ************************************************************************/
bool Config::LoadFromCard( void )
{
    nn::Result nnResult;
    nn::fs::FileInputStream ifile;
	bool retValue;

	//マウント（失敗時はセーブデータはないので即ＮＧとする）
	nnResult = nn::fs::MountSaveData();
	if( nnResult.IsFailure() )
    {
        //メディア発見できず（致命的エラー））
        if( nnResult <= nn::fs::ResultNotFound() )
        {
            uji::sys::Panic( "FAIL TO FIND BACKUP MEDIA!!" );
        }
        return false;
    }
    

	//リードオープン
	if( ifile.TryInitialize( FILE_NAME ).IsSuccess() )
	{
		retValue = LoadCommon( &ifile );
		ifile.Finalize();
	}else{
		retValue = false;
	}
	nn::fs::Unmount( "data:" );
	return retValue;
}

/************************************************************************
チェックコードを取得する

チェックコード範囲：０〜９９９９
 ************************************************************************/
int Config::GetCheckCode(void)
{
	u32 checkCode = CalcCrc( 0, reinterpret_cast<u8*>(&m_StaticConfig), sizeof(m_StaticConfig) ) ;
	return (int)( checkCode%10000 );
}

/************************************************************************

ConfigWindow

************************************************************************/


/************************************************************************
  パラメータの変更
  ************************************************************************/
void ConfigWindow::Open( void )
{
	int cursor = 0;
	int page   = 0;
	int id;

    uji::sys::Pad pad;
    uji::sys::SysApp *sysApp = uji::sys::SysApp::GetInstance();
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
	SetTitle( "CONFIGURATION" );

	Menu::m_WindowManager.CreateWindow(this, NN_GX_DISPLAY0,0,0 );
	Menu::m_WindowManager.SetManagerPadControlFlag(false);
    MakeMenuInformation();

    //メニューループ
	do {
        //パッド情報更新
        pad.UpdatePad();

        // 選択カーソルの移動処理
		if( pad.IsButtonRepeat( Pad::BUTTON_LEFT ) ){ page--   ; if( page<0 )	page   += m_TotalPage; cursor=0;			}
	 	if( pad.IsButtonRepeat( Pad::BUTTON_RIGHT) ){ page++   ; 			 	page   %= m_TotalPage; cursor=0;			} 
		if( pad.IsButtonRepeat( Pad::BUTTON_UP   ) ){ cursor-- ; if( cursor<0 ) cursor += m_MenuInformation[page].Number;	}
        if( pad.IsButtonRepeat( Pad::BUTTON_DOWN ) ){ cursor++ ; 				cursor %= m_MenuInformation[page].Number;	} 

        //実行
        if( pad.IsButtonDown( Pad::BUTTON_A ) ){
			ExecuteMenu( page, cursor );

			//トリガ情報クリア            
            pad.ClearTriggerFlag();            
		}
		
		//デフォルト値に戻す
		if( pad.IsButtonDown( Pad::BUTTON_X ) ){
			if( ShowMessage::Open( &Menu::m_WindowManager, "Do you initilize\n this parameter?", ShowMessage::SHM_OK_CANCEL ) )
			{ 
				id = m_MenuInformation[page].Index + cursor+1;
				*(m_Config->m_ConfigInformation[id].Data) = m_Config->m_ConfigInformation[id].DefaultData;
			}
		}

		//サブメニュー表示
		if( pad.IsButtonDown( Pad::BUTTON_START ) )
		{
			SubMenu();
            //トリガ情報クリア            
            pad.ClearTriggerFlag();            

		}

		ShowMenu( cursor, page );

        //ウインドウ処理
		Menu::m_WindowManager.Update();
        Menu::m_WindowManager.UpdatePad(pad);        

        // 上画面描画
        gfx->m_DrawFramework->SetRenderTarget(NN_GX_DISPLAY0);  
        gfx->m_DrawFramework->Clear();
        Menu::m_WindowManager.DrawDisplay0();
        gfx->m_DrawFramework->SwapBuffers();
        
		//説明文表示
		ShowExplanation();

		// 下画面描画        
        gfx->m_DrawFramework->SetRenderTarget(NN_GX_DISPLAY1);
        gfx->m_DrawFramework->Clear();        
        Menu::m_WindowManager.DrawDisplay1();
        gfx->m_DrawFramework->SwapBuffers();
        
        gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);                 

	}
    while( !pad.IsButtonDown(Pad::BUTTON_B) );

	Menu::m_WindowManager.DestroyWindow(this);

}

/************************************************************************
  メニュー情報の作成
  ************************************************************************/
void ConfigWindow::MakeMenuInformation( void ){

    int page = 0;
	int id   = 0;
	
    const ConfigWindow::ConfigMenu NullInformation = { 0, 0 };

    while( m_Config->m_ConfigInformation[id].Prefix[0] != '@' |
		   m_Config->m_ConfigInformation[id].Prefix[1] != '@'  ){ 

		if( m_Config->m_ConfigInformation[id].Prefix[0] == '@' ){

			//配列の拡張
			m_MenuInformation.push_back( NullInformation );

			//ページ先頭の処理
			m_MenuInformation[page].Index  = id;		
			m_MenuInformation[page].Number = 0;
			page++;
		}else{
			//ページ先頭以外の処理
			m_MenuInformation[page-1].Number++;
		}
		id++;
	}
	//ページ総数を保存
	m_TotalPage = page;

}

/**************************************************************************
メニューの表示

●引数
  Cursor	現在示しているカーソル位置
  Page		現在のページ（最初のページは０）

 *************************************************************************/
const char CONVERSION_TABLE[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";   //数値を文字に変換するためのテーブル

void ConfigWindow::ShowMenu( int Cursor, int Page )
{
    int i;
	int id;
	
	//メニュー名表示（見出し判別用の＠はスキップする）
    SetTextColor( ATTR_COLOR_GREEN );
	Printf( "\f%-42sPage%d/%d\n", m_Config->m_ConfigInformation[m_MenuInformation[Page].Index].Prefix+1, Page+1, m_TotalPage );    

	//メニュー本体を描画する
    for( i=0 ; i<m_MenuInformation[Page].Number ; i++ ){
		id = m_MenuInformation[Page].Index+1+i;		//対象の配列添字を算出

	
		//値がデフォールトと違えば色を変更にする
		if( *(m_Config->m_ConfigInformation[id].Data) != m_Config->m_ConfigInformation[id].DefaultData ){
            if( i!=Cursor ){
                SetTextColor( ATTR_COLOR_MAGENTA );
            }else{
                SetTextColor( ATTR_COLOR_CYAN );
            }
		}else{
            if( i!=Cursor ){
    		    SetTextColor( ATTR_COLOR_WHITE );
            }else{
                SetTextColor( ATTR_COLOR_RED);
            }
        }

        
		Printf( ID_STRING, Page+1, i+1 );							//識別番号表示

        Printf( PREFIX_STRING, m_Config->m_ConfigInformation[id].Prefix );				//変数の前の文字表示
		switch( m_Config->m_ConfigInformation[id].InputType ){
		  case Config::Input_DECIMAL:
			Printf( "      %04d", *( m_Config->m_ConfigInformation[id].Data ) );	//変数の値を表示
			break;
		  case Config::Input_DECIMAL5:
			Printf( "      %05d", *( m_Config->m_ConfigInformation[id].Data ) );
			break;
		  case Config::Input_DATA:
			Printf( "  %08X", 	 *( m_Config->m_ConfigInformation[id].Data ) );	
			break;
		  case Config::Input_DATA16:
			Printf( "      %04X", *( m_Config->m_ConfigInformation[id].Data ) );
			break;
		  case Config::Input_BOOL:
			Printf( "         %s", *( m_Config->m_ConfigInformation[id].Data )?"O":"X" );
			break;
		  case Config::Input_LIST:
			if( *(m_Config->m_ConfigInformation[id].Data) < GetListSize( m_Config->m_ConfigInformation[id].List ) ){
				Printf( "%10.10s", m_Config->m_ConfigInformation[id].List[ *(m_Config->m_ConfigInformation[id].Data) ]  );
			}
            break;
		  case Config::Input_ASCII3:
			Printf( "       %c%c%c", CONVERSION_TABLE[ *(m_Config->m_ConfigInformation[id].Data) / (36*36)      ]
                                   , CONVERSION_TABLE[ *(m_Config->m_ConfigInformation[id].Data) % (36*36) / 36 ]
                                   , CONVERSION_TABLE[ *(m_Config->m_ConfigInformation[id].Data) % (36*36) % 36 ]

            );
            break;
		  default:
			break;
		}
        Printf( SUFFIX_STRING, m_Config->m_ConfigInformation[id].Suffix   );			//変数の後ろの文字表示
    }
}    



/**************************************************************************
コンフィグ変更の実行部分
 *************************************************************************/
void ConfigWindow::ExecuteMenu( int page, int cursor )
{
	int id = m_MenuInformation[page].Index + cursor+1;

	const int VALIABLE_LOCATE_X2 = 27 +18;	//入力パラメータのX座標
	const int VALIABLE_LOCATE_X4 = 24 +18;
	const int VALIABLE_LOCATE_X8 = 20 +18;
	const int VALIABLE_LOCATE_X3 = 25 +18;


	//値がデフォールトと違えば色を黄色にする
	if( *(m_Config->m_ConfigInformation[id].Data) != m_Config->m_ConfigInformation[id].DefaultData )
    {
 	    SetTextColor( ATTR_COLOR_YELLOW );
    }else{
	    SetTextColor( ATTR_COLOR_WHITE );
	}

	Gotoxy( 0, cursor+1 );
    Printf( ID_STRING,	 	page+1, cursor+1 );							//識別番号表示
    Printf( PREFIX_STRING,	m_Config->m_ConfigInformation[id].Prefix );	//変数の前の文字
    Printf( "          " );											    //変数分の空白
    Printf( SUFFIX_STRING,  m_Config->m_ConfigInformation[id].Suffix );	//変数の後ろの文字表示
			
	switch( m_Config->m_ConfigInformation[id].InputType){
	  case Config::Input_DECIMAL:
		Gotoxy( VALIABLE_LOCATE_X4, cursor+1 );
		*(m_Config->m_ConfigInformation[id].Data) = InputDecimal( *(m_Config->m_ConfigInformation[id].Data) );
		break; 

	  case Config::Input_DECIMAL5:
		Gotoxy( VALIABLE_LOCATE_X4, cursor+1 );
		*(m_Config->m_ConfigInformation[id].Data) = InputDecimal5( *(m_Config->m_ConfigInformation[id].Data) );
		break; 

	  case Config::Input_DATA:
		Gotoxy( VALIABLE_LOCATE_X8, cursor+1 );
		*(m_Config->m_ConfigInformation[id].Data) = InputData( *(m_Config->m_ConfigInformation[id].Data) );
		break; 

	  case Config::Input_DATA16:
		Gotoxy( VALIABLE_LOCATE_X4, cursor+1 );
		*(m_Config->m_ConfigInformation[id].Data) = (u32)InputData16( (u16)(*(m_Config->m_ConfigInformation[id].Data)) );
		break; 

	  case Config::Input_BOOL:
		Gotoxy( VALIABLE_LOCATE_X2, cursor+1 );
		*(m_Config->m_ConfigInformation[id].Data) = (u32)(*(m_Config->m_ConfigInformation[id].Data)?false:true);
		break; 

	  case Config::Input_LIST:
		(*(m_Config->m_ConfigInformation[id].Data))++;
		if( *(m_Config->m_ConfigInformation[id].Data) >=GetListSize( m_Config->m_ConfigInformation[id].List ) ){
			*(m_Config->m_ConfigInformation[id].Data)= 0;
		}
		break; 

	  case Config::Input_ASCII3:
		Gotoxy( VALIABLE_LOCATE_X3, cursor+1 );
		*(m_Config->m_ConfigInformation[id].Data) = (u32)InputAscii3( (u16)(*(m_Config->m_ConfigInformation[id].Data)) );
		break; 

      default:
        break;
	}

}


/************************************************************************
  説明用の表示
 ************************************************************************/
void ConfigWindow::ShowExplanation( void ){
	Menu::m_SubWindow->Printf("\f");
	Menu::m_SubWindow->Printf("[USAGE]\n\n");
	Menu::m_SubWindow->Printf( " +    :Move\n" );
	Menu::m_SubWindow->Printf( " A    :Set\n" );
	Menu::m_SubWindow->Printf( " B    :Exit/Cancel\n");
	Menu::m_SubWindow->Printf( " X    :Set default\n" );
	Menu::m_SubWindow->Printf( " Start:Sub menu" );
}

/************************************************************************
  ロードやセーブをする為のサブメニューを表示
 ************************************************************************/
void ConfigWindow::SubMenu( void )
{
    Window *parentWin = Menu::m_WindowManager.GetActiveWindow();

	ClassMenu *m = new ClassMenu( "SUB MENU", 150, 100 );

    m->Add<ConfigWindow>( "Save",		this,	&ConfigWindow::SubMenuSave 		);
	m->Add<ConfigWindow>( "Load", 		this,	&ConfigWindow::SubMenuLoad 		);
	m->Add<ConfigWindow>( "Initialize",	this,	&ConfigWindow::SubMenuInitialize);
	m->Open();

	delete m;

	Menu::m_WindowManager.SetActiveWindow( parentWin );    

}

/************************************************************************
  セーブ（サブメニュー用）
  ************************************************************************/
void ConfigWindow::SubMenuSave( void )
{

	if( m_Config->Save() )
	{
		ShowMessage::Open( &Menu::m_WindowManager, "Success to save" );
	}else{
		ShowMessage::Open( &Menu::m_WindowManager, "Fail to save" );
	}
}




/************************************************************************
  ロード（サブメニュー用）
  ************************************************************************/
void ConfigWindow::SubMenuLoad( void )
{
	if( m_Config->Load() )
	{
		ShowMessage::Open( &Menu::m_WindowManager, "Success to load" );
	}else{
		ShowMessage::Open( &Menu::m_WindowManager, "Fail to load" );
	}
}

/************************************************************************
  初期化（サブメニュー用）
  ************************************************************************/
void ConfigWindow::SubMenuInitialize( void )
{
	m_Config->Initialize();
	ShowMessage::Open( &Menu::m_WindowManager, "Re-Initialized" );
}


/************************************************************************
  リストタイプのリスト数の計算

●引数
	表示リスト
●戻り値
	リスト数

  ************************************************************************/
static int  GetListSize( const char **List ){
	int Count=0;
	
	while( List[Count]!=NULL ){
		Count++;
	}
	return Count;
}
