
require "CIrpMan"
require "StateMachine"

CDialog =
{
	s_fSpeed			= 1 / 60,
	s_fYInDist			= 70,
	s_fYInDur			= 0.8,
	s_iMinGlintRate		= 1100,
	s_iMaxGlintRate		= 1500,
	s_iFirstGlint		= 300,
	
	State_TransitionIn	= 0,
	State_Showing		= 1,
}

----------------------------------------------------------------------------------------
-- CREATE/ATTACH
----------------------------------------------------------------------------------------

function CDialog:Attach( i_oObj )
	CIrpMan:Attach( i_oObj )
	StateMachine:Create( CDialog.State_TransitionIn, i_oObj )	
	CDialog:Bind( i_oObj )
	
	log("Attach");
	i_oObj:Init()

	i_oObj:SetOnUpdateEnabled( true )
	
	return i_oObj
end

----------------------------------------------------------------------------------------
-- PUBLIC
----------------------------------------------------------------------------------------

function CDialog:Init()
	
	if ( self.doMotionTransition == 1
			and ( self.inGame == nil 
				or self.inGame == false ) ) then

		local oIrp = self:CreateIrp( self:GetY() - CDialog.s_fYInDist, self:GetY(), CDialog.s_fYInDur, CIrpFuncs.mEaseOutQuint )

		oIrp.m_oHookContext = self

		oIrp.mOnChange = function( i_oIrp, i_oContext )
			
			local fVal = i_oIrp:GetVal()
			if ( fVal - math.floor( fVal ) < 0.5 ) then
				i_oContext:SetY( math.floor( fVal ) )
			else
				i_oContext:SetY( math.ceil( fVal ) )
			end
		end

		oIrp.mOnComplete = function( i_oIrp, i_oContext )
			i_oContext:SetState( CDialog.State_Showing )
		end
	end
	
	-- find all button glints
	self.m_iNextGlint = CDialog.s_iFirstGlint		-- first glint is faster
	self.m_aGlints = {}
	local children = self:GetChildren() 
	for i in pairs( children ) do
		local oMovie = children[ i ]
		if ( oMovie.GetSourceName ~= nil ) then
			local sName = oMovie:GetSourceName()
			local iIdx = string.len( sName ) - 5
			if ( iIdx > 0 ) then
				local sSubStr = string.sub( sName, iIdx )

				if ( sSubStr == "Button"
						and oMovie._buttonGlint ~= nil ) then
					table.insert( self.m_aGlints, oMovie )
				end
			end
		end
	end
end

function CDialog:OnEnterState( i_eNewState )
end

function CDialog:OnRunState( i_eState )
	
end

function CDialog:OnLeaveState( i_ePrevState )
end

function CDialog:OnUpdateDialog()
	self:UpdateIrps( CDialog.s_fSpeed )
	
	self.m_iNextGlint = self.m_iNextGlint - 1
	if ( self.m_iNextGlint <= 0 ) then
		self.m_iNextGlint = math.random( CDialog.s_iMinGlintRate, CDialog.s_iMaxGlintRate )
		log( "::::" .. self.m_iNextGlint )
		for i = 1, table.getn( self.m_aGlints ), 1 do
			if ( self.m_aGlints[ i ]._buttonGlint ~= nil ) then
				self.m_aGlints[ i ]._buttonGlint:SetPlaying( true )
			end
		end
	end
end

function CDialog:Bind( i_oObj )
	BindObj( CDialog, i_oObj )
	return i_oObj
end


----------------------------------------------------------------------------------------
-- PRIVATE
----------------------------------------------------------------------------------------


