/***********************************************************************/
/** 	© 2015 CD PROJEKT S.A. All rights reserved.
/** 	THE WITCHER® is a trademark of CD PROJEKT S. A.
/** 	The Witcher game is based on the prose of Andrzej Sapkowski.
/***********************************************************************/




class CR4MeditationClockMenu extends CR4MenuBase
{
	private var m_fxSetBlockMeditation		 	: CScriptedFlashFunction;
	private var m_fxSetCanMeditate			 	: CScriptedFlashFunction;
	private var m_fxSetBonusMeditationTime	 	: CScriptedFlashFunction;
	private var m_fxSetGeraltBackgroundVisible	: CScriptedFlashFunction;
	private var m_fxSet24HRFormat			 	: CScriptedFlashFunction;
	
	private var canMeditateWait				 	: bool;
	//modFriendlyMeditation begin
	//private var isGameTimePaused			 	: bool;
	//
	//private var BONUS_MEDITATION_TIME : int;
	//default BONUS_MEDITATION_TIME = 1;
	
	private var isPlayerMeditatingInBed			: bool;
	default isPlayerMeditatingInBed = false;
	private var meditationPressed				: bool;
	default meditationPressed = false;
	private var witcher							: W3PlayerWitcher;
	//modFriendlyMeditation end

	event  OnConfigUI()
	{	
		//modFriendlyMeditation begin
		//var commonMenu	: CR4CommonMenu;
		var locCode			: string;
		var initData		: W3SingleMenuInitData;
		var l_bed			: W3WitcherBed;
		
		witcher = GetWitcherPlayer();
		
		super.OnConfigUI();
		
		//witcher.MeditationClockStart(this);
		SendCurrentTimeToAS();
		if( witcher.GetMeditationStartedByClock() && witcher.IsSkippingTime() )
		{
			m_flashValueStorage.SetFlashInt( "meditation.clock.hours.update", GameTimeHours(theGame.GetGameTime()) );
			m_flashValueStorage.SetFlashInt( "meditation.clock.hours", CeilF(witcher.GetMeditationTargetTime()) );
		}
		
		m_fxSetBlockMeditation = m_flashModule.GetMemberFlashFunction( "SetBlockMeditation" );
		m_fxSet24HRFormat = m_flashModule.GetMemberFlashFunction( "Set24HRFormat" );
		m_fxSetGeraltBackgroundVisible = m_flashModule.GetMemberFlashFunction( "setGeraltBackgroundVisible" );
		m_fxSetBonusMeditationTime = m_flashModule.GetMemberFlashFunction( "setBonusMeditationTime" );
		
		m_fxSetBonusMeditationTime.InvokeSelfOneArg( FlashArgInt( witcher.fmedWitcherHouseBuffsHours ) );
		
		if( FactsQuerySum( "PlayerInsideInnerWitcherHouse" ) > 0 )
		{
			l_bed = (W3WitcherBed)theGame.GetEntityByTag( 'witcherBed' );
			if( l_bed.GetWasUsed() )
			{
				isPlayerMeditatingInBed = true;
				SetMeditationBonuses();
			}
		}
		
		//initData = (W3SingleMenuInitData)GetMenuInitData();
			
		if(GameplayFactsQuerySum("GamePausedNotByUI") > 0 && !thePlayer.IsInCombat())
		{
			canMeditateWait = false;
			witcher.MeditationRestoring(0);
		}
		else
		{
			theGame.Unpause("menus");
			canMeditateWait = witcher.ModCanMeditate(isPlayerMeditatingInBed);
			theGame.Pause("menus");
		}
			
		//if (canMeditateWait)
		//{
		//	m_fxSetGeraltBackgroundVisible.InvokeSelfOneArg( FlashArgBool(true) );
		//}
		
		m_fxSetBlockMeditation.InvokeSelfOneArg( FlashArgBool( !canMeditateWait ) );
		
		locCode = GetCurrentTextLocCode();
		m_fxSet24HRFormat.InvokeSelfOneArg(FlashArgBool(locCode != "EN"));
		
		RegisterActions();
		//modFriendlyMeditation end
	}
	
	event  OnClosingMenu()
	{
		//modFriendlyMeditation begin
		//var commonMenu : CR4CommonMenu;
		
		theGame.GetGuiManager().SendCustomUIEvent( 'ClosedMeditationClockMenu' );
		
		//commonMenu = (CR4CommonMenu)m_parentMenu;
		//if (commonMenu)
		//{
		//	commonMenu.SetMeditationMode(false);
		//	
		//	if( commonMenu.GetIsPlayerMeditatingInBed() )
		//	{
		//		GetWitcherPlayer().ManageSleeping();
		//	}
		//}
		//
		//GetWitcherPlayer().MeditationClockStop();
		UnregisterActions();
		//modFriendlyMeditation end
	}
	
	event  OnCloseMenu()
	{
		//modFriendlyMeditation begin
		//if(thePlayer.GetCurrentStateName() == 'MeditationWaiting')
		//{
		//	MeditatingEnd();
		//}
		//
		//if (!theGame.IsPaused())
		//{
		//	theGame.Pause("menus");
		//}
		
		if( !meditationPressed && isPlayerMeditatingInBed )
		{
			if( !witcher.IsMeditating() && !witcher.IsSkippingTime() )
				witcher.ManageSleeping();
		}
		
		UnregisterActions();
		//modFriendlyMeditation end
		

		
		CloseMenu();
		
		if( m_parentMenu )
		{
			m_parentMenu.ChildRequestCloseMenu();
		}
	}
	
	private function SetMeditationBonuses():void
	{
		var defManager	: CDefinitionsManagerAccessor;
		var flashObject	: CScriptedFlashObject;
		var flashArray	: CScriptedFlashArray;
		var bedEntity	: W3WitcherBed;
		var bedLevel	: int;
		var min, max    : SAbilityAttributeValue;
		var arrStr		: array< string >;
		var abilityVal  : float;
		var durationStr : string;
		var bedLevelString	: string;
		
		defManager = theGame.GetDefinitionsManager();
		bedEntity = (W3WitcherBed)theGame.GetEntityByTag( 'witcherBed' );
		flashArray = m_flashValueStorage.CreateTempFlashArray();
		
		
		
		if( bedEntity )
		{
			flashObject = m_flashValueStorage.CreateTempFlashObject();
			
			bedLevel = bedEntity.GetBedLevel();
			
			if( bedLevel > 0 )
			{
				flashObject.SetMemberFlashBool( "available",  true );
			}
			else
			{
				flashObject.SetMemberFlashBool( "available",  false );
				bedLevel = 1;
			}
			
			bedLevelString = "bed_level_" + IntToString( bedLevel );
			
			arrStr.PushBack( IntToString( bedLevel ) );
			flashObject.SetMemberFlashString( "title", GetLocStringByKeyExtWithParams( "panel_title_buff_bed",,, arrStr ) + " " + GetLocStringByKeyExt( bedLevelString ) );
			arrStr.Clear();
			
			defManager.GetAbilityAttributeValue( 'WellRestedEffect', 'vitality', min, max);
			abilityVal = CalculateAttributeValue( min );
			if( bedLevel > 1 )
				abilityVal *= 2;
			arrStr.PushBack( FloatToStringPrec( abilityVal, 0 ) );
			flashObject.SetMemberFlashString( "description", GetLocStringByKeyExtWithParams( "panel_buff_bed_descr",,, arrStr ) );
			arrStr.Clear();
			
			defManager.GetAbilityAttributeValue( 'WellRestedEffect', 'duration', min, max);
			abilityVal = CalculateAttributeValue( min );
			if( bedLevel == 2 )
				abilityVal *= 2;
			arrStr.PushBack( FloatToString( abilityVal / 60 ) );
			durationStr = GetLocStringByKeyExtWithParams( "panel_buff_duration",,, arrStr );
			flashObject.SetMemberFlashString( "duration", durationStr );
			arrStr.Clear();
			
			flashObject.SetMemberFlashString( "type", "bed" );
			flashArray.PushBackFlashObject( flashObject );
		}
		
		
		
		flashObject = m_flashValueStorage.CreateTempFlashObject();
		
		defManager.GetAbilityAttributeValue( 'BookshelfBuffEffect', 'nonhuman_exp_bonus_when_fatal', min, max);
		abilityVal = CalculateAttributeValue( min );
		arrStr.PushBack( FloatToStringPrec( ( abilityVal * 100 ), 0 ) );
		flashObject.SetMemberFlashString( "description", GetLocStringByKeyExtWithParams( "panel_buff_bookshelf_descr",,, arrStr ) );
		arrStr.Clear();
		
		defManager.GetAbilityAttributeValue( 'BookshelfBuffEffect', 'duration', min, max);
		abilityVal = CalculateAttributeValue( min );
		arrStr.PushBack( FloatToString( abilityVal / 60 ) );
		durationStr = GetLocStringByKeyExtWithParams( "panel_buff_duration",,, arrStr );
		flashObject.SetMemberFlashString( "duration", durationStr );
		arrStr.Clear();
		
		flashObject.SetMemberFlashString( "title", GetLocStringByKeyExt( "panel_title_buff_bookshelf" ) );
		flashObject.SetMemberFlashString( "type", "bookshelf" );
		flashObject.SetMemberFlashBool( "available",  true );
		
		flashArray.PushBackFlashObject( flashObject );
		
		
		
		flashObject = m_flashValueStorage.CreateTempFlashObject();
		flashObject.SetMemberFlashString( "title", GetLocStringByKeyExt( "panel_title_buff_alchemy_table" ) );
		flashObject.SetMemberFlashString( "duration", "" );
		flashObject.SetMemberFlashString( "type", "alchemytable" );
		flashArray.PushBackFlashObject( flashObject );
		
		arrStr.PushBack( IntToString( theGame.params.QUANTITY_INCREASED_BY_ALCHEMY_TABLE ) );
		flashObject.SetMemberFlashString( "description", GetLocStringByKeyExtWithParams( "panel_buff_alchemy_table_descr",,, arrStr ) );
		arrStr.Clear();
		
		if( FactsDoesExist( "AlchemyTableExists" ) )
		{
			flashObject.SetMemberFlashBool( "available",  true );
		}
		else
		{
			flashObject.SetMemberFlashBool( "available",  false );
		}
		
		
		
		flashObject = m_flashValueStorage.CreateTempFlashObject();
		flashObject.SetMemberFlashString( "title", GetLocStringByKeyExt( "panel_title_buff_stables" ) );
		flashObject.SetMemberFlashString( "type", "stable" );
		
		defManager.GetAbilityAttributeValue( 'HorseStableBuff', 'stamina', min, max );
		abilityVal = CalculateAttributeValue( min );
		arrStr.PushBack( FloatToStringPrec( abilityVal, 0 ) );
		flashObject.SetMemberFlashString( "description", GetLocStringByKeyExtWithParams( "panel_buff_stables_descr",,,  arrStr ) );
		arrStr.Clear();
		
		defManager.GetAbilityAttributeValue( 'HorseStableBuffEffect', 'duration', min, max );
		abilityVal = CalculateAttributeValue( min );
		arrStr.PushBack( FloatToString( abilityVal / 60 ) );
		durationStr = GetLocStringByKeyExtWithParams( "panel_buff_duration",,, arrStr );
		flashObject.SetMemberFlashString( "duration", durationStr );
		arrStr.Clear();
		
		if( FactsDoesExist( "StablesExists" ) )
		{
			flashObject.SetMemberFlashBool( "available",  true );
		}
		else
		{
			flashObject.SetMemberFlashBool( "available",  false );
		}
		
		flashArray.PushBackFlashObject( flashObject );
		
		
		
		m_flashValueStorage.SetFlashArray( "meditation.bonus", flashArray );
	}
	
	function SetButtons()
	{
		AddInputBinding("panel_button_common_exit", "escape-gamepad_B", -1);
		//modFriendlyMeditation begin
		if( witcher.IsMeditating() || witcher.IsSkippingTime() )
			AddInputBinding("panel_button_meditation_stop", "gamepad_Y", IK_C);
		//modFriendlyMeditation end
		super.SetButtons();
	}
	
	//modFriendlyMeditation begin
	private var actionsRegistered : bool; default actionsRegistered = false;
	
	function RegisterActions()
	{
		if(!actionsRegistered)
		{
			theInput.StoreContext( 'MEDITATION_CLOCK_CONTEXT' );
			theInput.RegisterListener( this, 'OnMeditationStop', 'MeditationStop' );
			actionsRegistered = true;
		}
	}
	
	function UnregisterActions()
	{
		if(actionsRegistered)
		{
			theInput.UnregisterListener( this, 'OnMeditationStop' );
			theInput.RestoreContext( 'MEDITATION_CLOCK_CONTEXT', false );
			actionsRegistered = false;
		}
	}
	
	event OnMeditationStop( action : SInputAction )
	{
		if( IsPressed(action) )
		{
			witcher.ModEndMeditation();
		}
	}
	//modFriendlyMeditation end
	
	public function UpdateCurrentHours( ):void
	{
		var timeHours : int = GetCurrentDayTime( "hours" );
		var	timeMinutes : int = GetCurrentDayTime( "minutes" );
		m_flashValueStorage.SetFlashInt( "meditation.clock.hours.update", timeHours );
		m_flashValueStorage.SetFlashInt( "meditation.clock.minutes", timeMinutes );
	}
	
	public function SendCurrentTimeToAS():void
	{
		var  timeHours : int = GetCurrentDayTime( "hours" );
		var  timeMinutes : int = GetCurrentDayTime( "minutes" );
		
		m_flashValueStorage.SetFlashInt( "meditation.clock.hours", timeHours );
		m_flashValueStorage.SetFlashInt( "meditation.clock.minutes", timeMinutes );
	}
	
	event  OnMeditate( dayTime : float )
	{
		var medd : W3PlayerWitcherStateMeditation;
		
		if (!canMeditateWait)
		{
			ShowDisallowedNotification();			
		}
		else
		{		
			if (theGame.IsPaused())
			{
				theGame.Unpause("menus");
			}
			
			//modFriendlyMeditation begin
			meditationPressed = true;
			UnregisterActions();
			if( witcher.ModStartMeditation( isPlayerMeditatingInBed, true, CeilF(dayTime) ) )
			{
				OnPlaySoundEvent( "gui_meditation_start" );
				
				//LogChannel('CLOCK',"	** OnMeditate ** ");
				//if(dayTime == GameTimeHours(theGame.GetGameTime()))
				//	return false;
				//
				//medd = (W3PlayerWitcherStateMeditation)thePlayer.GetCurrentState();
				//medd.MeditationWait(CeilF(dayTime));
				//
				//
				//StartWaiting();
			}
			//modFriendlyMeditation end
		}
	} 
	
	event  OnMeditateBlocked()
	{
		ShowDisallowedNotification();
	}
	
	event  OnStopMeditate()
	{
		//modFriendlyMeditation begin
		//var waitt : W3PlayerWitcherStateMeditationWaiting;
	    //
		//if(thePlayer.GetCurrentStateName() == 'MeditationWaiting')
		//{
		//	waitt = (W3PlayerWitcherStateMeditationWaiting)thePlayer.GetCurrentState();
		//	if(waitt)
		//		waitt.RequestWaitStop();
		//}
		//
		//MeditatingEnd();
		witcher.ModEndMeditation();
		//modFriendlyMeditation end
	}
	
	function GetCurrentDayTime( type : string ) : int 
	{
		var gameTime : GameTime = theGame.GetGameTime();
		var currentDays : int;
		var currentHours : int;
		var currentMinutes : int;
		var currentTime : int;
		
		switch( type )
		{
			case "days" :
			{
				currentTime = GameTimeDays( gameTime );
				break;
			}
			case "hours" :
			{
				currentDays = GameTimeDays( gameTime );
				currentHours = GameTimeHours( gameTime );
				currentTime = currentHours ;
				break;
			}
			case "minutes" :
			{
				currentDays = GameTimeDays( gameTime );
				currentHours = GameTimeHours( gameTime );
				currentMinutes = GameTimeMinutes( gameTime );
				currentTime = currentMinutes;
				break;
			}	
		}
		return currentTime;
	}
	
	
	
	
	//modFriendlyMeditation begin
	//public function StartWaiting():void
	//{
	//	theGame.GetCityLightManager().SetUpdateEnabled( false );
	//	m_flashValueStorage.SetFlashBool( "meditation.clock.blocked", true );
	//	SetMenuNavigationEnabled(false);
	//}
	//
	//public function StopWaiting():void
	//{
	//	m_flashValueStorage.SetFlashBool( "meditation.clock.blocked", false );
	//	SetMenuNavigationEnabled(true);
	//}
	//
	//function MeditatingEnd()
	//{
	//	theGame.GetCityLightManager().ForceUpdate();
	//	theGame.GetCityLightManager().SetUpdateEnabled( true );
	//	m_flashValueStorage.SetFlashBool( "meditation.clock.blocked", false );
	//	SetMenuNavigationEnabled(true);
	//}
	//modFriendlyMeditation end
	
	function PlayOpenSoundEvent()
	{
		
		
	}
	
	private final function ShowDisallowedNotification()
	{		
		if(thePlayer.IsInCombat())
		{
			showNotification(GetLocStringByKeyExt("menu_cannot_perform_action_combat"));
		}
		else
		{
			showNotification(GetLocStringByKeyExt( "menu_cannot_perform_action_now" ));
		}
		
		OnPlaySoundEvent("gui_global_denied");
	}
}