﻿/*---------------------------------------------------------------------------*
  Project:  
  File:     sys_PowerButton.cpp
 *---------------------------------------------------------------------------*/
#include "sys_PowerButton.h"
#include "../eva/gyro/gyro_UdsClient.h"    
#include <nn/ns/CTR/ns_Shell.h>        

namespace uji {
namespace sys {
    

nn::os::Thread PowerButton::PowerButtonThread;
nn::os::LightEvent PowerButton::m_ThreadBreak;


void PowerButton::StartMonitoring()
{
    m_ThreadBreak.Initialize(false);
    PowerButtonThread.StartUsingAutoStack(ThreadFunc, this, STACK_SIZE, DEFAULT_PRIORITY);
}

void PowerButton::StopMonitoring()
{
    m_ThreadBreak.Signal();    
        
    PowerButtonThread.Join();
    PowerButtonThread.Finalize();            
}

void PowerButton::MonitoringProcess()
{
    while(true)
    {
// 通常SDKの方法        
#if 0        
        if ( nn::applet::IsExpectedToProcessPowerButton() )
        {
            nn::applet::ProcessPowerButton();
            nn::applet::WaitForStarting();

            if ( nn::applet::IsExpectedToCloseApplication() )
            {
                // アプリケーションの終了処理
                // TODO:
                
                nn::applet::PrepareToCloseApplication();
                nn::applet::CloseApplication();
            }

            // GPU レジスタ設定の復帰
            nngxUpdateState(NN_GX_STATE_ALL);
            nngxValidateState(NN_GX_STATE_ALL,GL_TRUE);            
        }
        
        if (m_ThreadBreak.TryWait())
        {
            NN_LOG("Exit: MonitoringProcess\n");            
            break;   
        }        
        
// シャットダウン時間短縮
#else
        // 電源ボタン短押しでシステムにシャットダウン通知を投げる
        if( nn::applet::IsExpectedToProcessPowerButton())
        {
#ifdef EVA_GYRO_C            
            // 接続中のネットワークから離脱
            uji::eva::GyroUdsClient::DisconnectNetwork();
#endif            
            nn::ns::CTR::ShutdownAsync();
        }

        // シャットダウンが始まったらアプリを終了させる
        if ( nn::applet::IsExpectedToCloseApplication())
        {
            // アプリの終了処理
            // ・・・
                        
            nn::applet::PrepareToCloseApplication();
            nn::applet::CloseApplication();
        }    
#endif            
        nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromMilliSeconds(20));                
    }
}    

void PowerButton::ThreadFunc(void* param)
{
    PowerButton* pPowerButton = reinterpret_cast<PowerButton*>(param);
    pPowerButton->MonitoringProcess();
}


}   // namespace
}
