require "StandardMouseButton"
require "StateMachine"
require "CIrpMan"

-- reserve constructor
if ( ISpyPanel == nil ) then
	ISpyPanel = 
	{
		name					= "ISpyPanel",

		State_Playing			= 0,
	}
end

ISpyPanel.s_fInitWaitTime				= 0.1
ISpyPanel.s_fTransitionInDur			= 1.0	 -- in secs
ISpyPanel.s_iBluebirdMeterCount			= 5
ISpyPanel.s_fBluebirdMeterDurMod		= 2

-- color (dup)
--ISpyPanel.s_fBirdHintTrailDecayRate		= 0.005
--ISpyPanel.s_fBirdHintTrailStartAlpha	= 0.19

-- grayscale
ISpyPanel.s_fBirdHintTrailDecayRate		= 0.025
ISpyPanel.s_fBirdHintTrailStartAlpha	= 0.5

-- light part of bird
--ISpyPanel.s_iBirdHintTrailColor			= 0xFFFFFF
ISpyPanel.s_fBirdFlapSpeed				= 0.1

-- dark part of bird 
ISpyPanel.s_iBirdHintTrailColor			= 0xFFBE00

function ISpyPanel:Create(  )
	
	-- The main screen container
	local instance = root.dialogs[ self.name ];
	CIrpMan:Attach( instance )
	StateMachine:Create( ISpyPanel.State_Playing, instance )
	
	-- The ok button
	local bookButton = instance.bookButton
	local menuButton = instance.menubutton
	local listMask = instance.listMask
	local itemCount = instance.list.itemCountText
--	local cupid = instance.top.cupid
	--local clockHand = cupid.hand
	--local clockGlow = cupid.glow
	local hintbutton = instance.clues.hintbutton
	local pauseButton = instance.top.pauseButton
	local lastsecond = -1;
	local clockframe = 0;
	
	-- VV
	--local apart_arrow_left = instance.apart_arrow_left
	--local apart_arrow_right = instance.apart_arrow_right
	
	local hintHandles = {}
	
	instance.internalList = {}
	
	instance.flashTime = 0;
	
	-- make sure we get updates
	instance:SetOnUpdateEnabled( true );
	
	if ( IsRetail() == false ) then
		instance:AddAsGlobalHandler()
		function instance:OnCharDown( i_iChar )
			if ( i_iChar == 190 ) then		-- '.'
				log( "RELOAD LUA!" )
				console( "lua.dofile ISpyPanel.lua" )
			elseif ( i_iChar == 188 ) then	-- ','
				log( "RELOAD ART!" )
				console( "library.reloadpackage input" )
				console( "library.reloadpackage ui" )
			end
		end
	end	
	
	function instance:UpdateClock()
		local iColor = 0x0

		if ( self.Relaxed ) then
			
			iColor = 0x999999
			
			pauseButton:SetOpacity( 0.3 )
			pauseButton:SetInputEnabled( false )
--			clockGlow:SetVisible( false )
--			clockGlow:SetInputEnabled( false )
		else
			pauseButton:SetOpacity( 1.0 )
			pauseButton:SetInputEnabled( true )
--			clockGlow:SetVisible( true )
--			clockGlow:SetInputEnabled( true )
		end
		
		self.m_oMinutesText:SetColor( iColor )
		self.m_oColonText:SetColor( iColor )
		self.m_oSecondsText:SetColor( iColor )
	end
	
	-- The main init function
	function instance:Init( )
		
		ISpyPanel.G = self

		self.m_oMinutesText = self.top.minutes
		self.m_oColonText = self.top.colon
		self.m_oSecondsText = self.top.seconds
		self.m_oBluebirds = self.top.bluebirdCounter
--		self.m_oCupid = self.top.cupid
		self.m_fArrowFadeInOn = 0
		self.m_iLastBluebirdCount = 0
		self.m_iTargetBluebirdCount = 0
		self.m_oBluebirdMeterIrp = nil
		self.m_oBonusArrowIrp = nil
		self.m_oHintCounterText = instance.clues.hintbutton.hintcounter
		self.m_bLockHintCounter = false
		self.m_oHintButton = instance.clues.hintbutton

		self.m_oHintCounterText.m_fOrigX = self.m_oHintCounterText:GetX()
		self.m_oHintCounterText.m_fOrigY = self.m_oHintCounterText:GetY()
		self.m_oHintCounterText.m_fOrigWidth = self.m_oHintCounterText:GetWidth()
		self.m_oHintCounterText.m_fOrigHeight = self.m_oHintCounterText:GetHeight()

		instance:SetPosition( 0, 0 )
		
		self:UpdateClock()
		
		local minutes = math.floor( instance.Time / 60 )
		local seconds = math.floor( math.mod( instance.Time , 60 ) )
		local secondsStr = tostring( seconds );
		
		if( seconds <= 9 ) then
			secondsStr = "0"..seconds;
		end
		
		self.m_oMinutesText:SetText( tostring( minutes ) )
		self.m_oSecondsText:SetText( secondsStr )
		
		itemCount:SetText( "" .. instance.totalItems )
		
		
		
		StandardMouseButton( bookButton );
		bookButton:Init( )
		StandardMouseButton( menuButton );
		menuButton:Init( )
		StandardMouseButton( hintbutton );
		hintbutton:Init( )
		StandardMouseButton( pauseButton );
		pauseButton:Init( )
		pauseButton:DisableSound()		
		
		instance:updateUI( )

		--VV
		--StandardMouseButton( apart_arrow_left );
		--apart_arrow_left:Init( )		
		--StandardMouseButton( apart_arrow_right );
		--apart_arrow_right:Init( )		
		
		self.m_oHintCounterText:SetFrame( tonumber( instance.vishintcount ) )

		self.listMask:SetVisible( false )

		-- set list masking
		self.listMaskTop:SetVisible( false )
		
		self:SetBluebirdCount( self.Bluebirds, true )
	end
	
	-- add an item to the find list
	function instance:AddItem( i_Item )
		
		--log("AddItem " .. i_Item)
		local newItem = {}
		newItem.string = i_Item
		newItem.sPopup = ""
		newItem.found = false
		newItem.super = false
		newItem.needPopup = false
		
		table.insert( self.internalList, newItem )
	end
	
	-- add an item to the find list
	function instance:AddSuperItem( i_Item )
		
		local newItem = {}
		newItem.string = i_Item
		newItem.sPopup = ""
		newItem.found = false
		newItem.super = true
		newItem.needPopup = false
		
		table.insert( self.internalList, newItem )
	end
	
		-- add an item to the find list
	function instance:AddItemPopup( i_Item, i_Popup )
		
		--log("AddItemPopup " .. i_Item .. " " .. i_Popup)
		local newItem = {}
		newItem.string = i_Item
		newItem.sPopup = i_Popup
		newItem.found = false
		newItem.super = false
		newItem.needPopup = true
		
		table.insert( self.internalList, newItem )
	end
	
	-- add an item to the find list
	function instance:AddSuperItemPopup( i_Item, i_Popup)
		
		local newItem = {}
		newItem.string = i_Item
		newItem.sPopup = i_Popup
		newItem.found = false
		newItem.super = true
		newItem.needPopup = true
		
		table.insert( self.internalList, newItem )
	end
	
	function instance:SetItemFound( i )
		if ( self.internalList[i] ~= nil ) then
			if(self.internalList[i].needPopup == false) then
				self.internalList[i].string = self:GetLastItemName()
			else
				self.internalList[i].string = self:GetLastItemNameCutted()
				self.internalList[i].sPopup = self:GetLastItemName()
			end
			self.internalList[i].status = true
		end
	end
	
	function instance:SetItemHidden( i )
		if ( self.internalList[i] ~= nil ) then
			if(self.internalList[i].needPopup == false) then
				self.internalList[i].string = self:GetLastItemName()
			else
				self.internalList[i].string = self:GetLastItemNameCutted()
				self.internalList[i].sPopup = self:GetLastItemName()
			end
			self.internalList[i].status = false
		end
	end
	
	function instance:SetFlashTime( flash )
		self.flashTime = flash
	end
	
	function instance:ClearItemList()
		self.internalList = {}
	end

	-- Handle keyboard input for the dialog
	function instance:OnCharDown( i_Key )
		--[[
		if ( IsDebug() ) then
			if ( i_Key == "R"  ) then
				self:Reload()
			end
		end
		--]]
	end
	
	function instance:Reload()
		log( "RELOAD!" )
		console( "lua.dofile ISpyPanel.lua" )
		ISpyPanel:Create( )
		self:HintHint()
	end
	
	function instance:OnHint()

--		self.m_oCupid.cupid.arrow.m_fOpacity = 0
--		self.m_oCupid.cupid.arrow:SetOpacity( 0 )
		self.m_fArrowFadeInOn = self:GetTimeInState() + 1.75
	end
		
	function instance:GetSplinePathAndShow( i_locX, i_locY, i_itemWidth )
		local aRet = self:GetSplinePath( i_locX, i_locY, i_itemWidth )

		self:CanvasDrawLine( 0, 300, 800, 300, 0xffffff00 )
		self:CanvasDrawLine( 450, 0, 450, 600, 0xffffff00 )

	
		for i = 1, #aRet, 1 do
			self:CanvasDrawCircle( aRet[ i ][ 1 ], aRet[ i ][ 2 ], 20, 0xffffff00, 32 )
			self:CanvasDrawTextLine( aRet[ i ][ 1 ], aRet[ i ][ 2 ], 20, 0xffffff00, tostring( i - 1 ) )
			if ( i > 1 ) then
				if ( i == 2 or i == #aRet ) then
					self:CanvasDrawLine( aRet[ i - 1 ][ 1 ], aRet[ i - 1 ][ 2 ], aRet[ i ][ 1 ], aRet[ i ][ 2 ], 0xffff0000 )
				else
					self:CanvasDrawLine( aRet[ i - 1 ][ 1 ] - 1, aRet[ i - 1 ][ 2 ] - 1, aRet[ i ][ 1 ] - 1, aRet[ i ][ 2 ] - 1, 0xffff0000 )
					self:CanvasDrawLine( aRet[ i - 1 ][ 1 ], aRet[ i - 1 ][ 2 ], aRet[ i ][ 1 ], aRet[ i ][ 2 ], 0xffff0000 )
					self:CanvasDrawLine( aRet[ i - 1 ][ 1 ] + 1, aRet[ i - 1 ][ 2 ] + 1, aRet[ i ][ 1 ] + 1, aRet[ i ][ 2 ] + 1, 0xffff0000 )
				end
			end
		end
	
		return aRet
	end

	function instance:GetSplinePath( i_locX, i_locY, i_itemWidth )
		
		local fHalfWidth = 450.0;
		local fHalfHeight = 300.0;
		
		local aRet = {}
		
		-- first and last points are spline control points that are not traversed
		-- (see http://www.mvps.org/directx/articles/catmull/ )
		
		local fStartX = 90
		local fStartY = 65

		local fItemSpacing = i_itemWidth / 2 + 30
		
		if ( i_locX < fHalfWidth and i_locY < fHalfHeight ) then
		
			-- UPPERLEFT
		
			-- adjust location to be slightly away from object
			local fAdjLocX = i_locX + fItemSpacing
			local fDeltaX = fAdjLocX - fStartX
			local fDeltaY = i_locY - fStartY
			local fDist = math.sqrt( fDeltaX * fDeltaX + fDeltaY * fDeltaY )

			local fMult = fDist * 0.002

			table.insert( aRet,	{	500,					60,									0.0 } )
			table.insert( aRet,	{	fStartX,				fStartY,							0.0 } )
			table.insert( aRet,	{	fStartX + 315 * fMult,	fStartY + 440 * fMult,				1.0 } )
			table.insert( aRet,	{	fStartX + 565 * fMult,	fStartY + 340 * fMult,				1.2 } )
			table.insert( aRet,	{	fStartX + 615 * fMult,	fStartY + 190 * fMult,				1.2 } )
			table.insert( aRet,	{	fStartX + 515 * fMult,	fStartY + 80 * fMult,				1.2 } )
			table.insert( aRet,	{	fAdjLocX,				i_locY,								1.3 } )
			table.insert( aRet,	{	fStartX + 315 * fMult,	fStartY + 440 * fMult,				0.0 } )
		
		elseif ( i_locX >= fHalfWidth and i_locY < fHalfHeight ) then
			
			-- UPPERRIGHT
			
			local fAdjLocX = i_locX - fItemSpacing

			table.insert( aRet,	{	500,					60,									0.0 } )
			table.insert( aRet,	{	fStartX,				fStartY,							0.0 } )
			table.insert( aRet,	{	250,					350,								0.9 } )
			table.insert( aRet,	{	550,					500,								1.0 } )
			table.insert( aRet,	{	700,					350,								1.2 } )
			table.insert( aRet,	{	fAdjLocX,				i_locY,								1.0 } )
			table.insert( aRet,	{	fAdjLocX,				i_locY,								0.0 } )

		elseif ( i_locX < fHalfWidth and i_locY >= fHalfHeight ) then

			-- LOWERLEFT
			
			local fAdjLocX = i_locX + fItemSpacing

			table.insert( aRet,	{	500,					60,									0.0 } )
			table.insert( aRet,	{	fStartX,				fStartY,							0.0 } )
			table.insert( aRet,	{	300,					550,								1.0 } )
			table.insert( aRet,	{	650,					400,								1.2 } )
			table.insert( aRet,	{	525,					250,								1.2 } )
			table.insert( aRet,	{	fAdjLocX,				i_locY,								1.2 } )
			table.insert( aRet,	{	fAdjLocX,				i_locY,								0.0 } )

		elseif ( i_locX >= fHalfWidth and i_locY >= fHalfHeight ) then

			-- LOWERRIGHT 
			
			local fAdjLocX = i_locX - fItemSpacing

			table.insert( aRet,	{	500,					60,									0.0 } )
			table.insert( aRet,	{	fStartX,				fStartY,							0.0 } )
			table.insert( aRet,	{	600,					200,								1.0 } )
			table.insert( aRet,	{	400,					400,								1.3 } )
			table.insert( aRet,	{	fAdjLocX,				i_locY,								1.0 } )
			table.insert( aRet,	{	fAdjLocX,				i_locY,								0.0 } )

		end

		for i = 3, #aRet - 1, 1 do
			local fDeltaX = aRet[ i ][ 1 ] - aRet[ i - 1 ][ 1 ]
			local fDeltaY = aRet[ i ][ 2 ] - aRet[ i - 1 ][ 2 ]
			
			local fDist = math.sqrt( fDeltaX * fDeltaX + fDeltaY * fDeltaY )
			aRet[ i ][ 3 ] = aRet[ i ][ 3 ] * fDist * 0.0015
		end
		
		return aRet
	end

	function instance:SetBluebirdCount( i_iCount, i_bAllowReset )
		
		log( "HEREHERE" .. i_iCount )
		local iCount = math.mod( i_iCount, ISpyPanel.s_iBluebirdMeterCount )
		if ( i_iCount > 0 and iCount == 0 and i_bAllowReset ~= true ) then
			iCount = ISpyPanel.s_iBluebirdMeterCount
		end
		
		local oCounter = self.m_oBluebirds
		oCounter:SetFrame( i_iCount )
	end
	
	-- The Album button
	function bookButton:Init( )
		function bookButton:Pressed( )
			instance:ScreenEvent( "Albumn" , "ISpyPanel" )
		end
	end

	-- The help button
	function hintbutton:Init( )
		function hintbutton:Pressed( )
			instance:ScreenEvent( "hint" , "ISpyPanel" )
		end
	end
		
	-- The help button
	function menuButton:Init( )
		function menuButton:Pressed( )
			--[[
			if ( IsDebug() ) then
				instance:Reload()
			end
			--]]
			
			instance:ScreenEvent( "GameMenu" , "ISpyPanel" )
		end
	end
	
	-- VV
--[[	function apart_arrow_left:Init()
		log("init")
		function apart_arrow_left:Pressed( )
			log("pressed")
			instance:ScreenEvent( "ScrollLeft", "ISpyPanel" )
		end
	end
	function apart_arrow_right:Init()
		function apart_arrow_right:Pressed( )
			instance:ScreenEvent( "ScrollRight", "ISpyPanel" )
		end
	end  --]]

	-- The help button
	function pauseButton:Init( )
		function pauseButton:Pressed( )
			instance:ScreenEvent( "PauseGame", "ISpyPanel" )
		end
		--function clockGlow:OnLeftMouseUp( )
		--	instance:ScreenEvent( "PauseGame", "ISpyPanel" )
		--end
	end
	
	function instance:OnUpdate( )
		self:RunStateMachine()
	end	
	
	function instance:OnRunState( i_eState )
		-- dont update the UI if the board it reflects has been lost
		if ( self.Lost == 1 ) then
			return
		end
	
		local fTimeElapsed = self:GetTimeInState()
		
		self:UpdateIrps( 1 / 60 )
		
--		local oCupidArrow = self.m_oCupid.cupid.arrow
--		if ( fTimeElapsed > self.m_fArrowFadeInOn 
--				and oCupidArrow ~= nil
--				and oCupidArrow.m_fOpacity ~= nil 
--				and oCupidArrow:GetVisible() ) then
--			oCupidArrow.m_fOpacity = math.min( 1, oCupidArrow.m_fOpacity + 0.02 )
--			oCupidArrow:SetOpacity( oCupidArrow.m_fOpacity )
--		end
	
		if ( i_eState == ISpyPanel.State_Playing ) then

			self:UpdateClock()

			local minutes = math.floor( instance.Time / 60 )
			local seconds = math.floor( math.mod( instance.Time , 60 ) )
			
			if( minutes < 0 or seconds < 0 ) then
				minutes = 0
				seconds = 0	
			end
			
			self.m_oMinutesText:SetText( tostring( minutes ) )
			
			local secondsStr = tostring( seconds );
			
			if( seconds <= 9 ) then
				secondsStr = "0"..seconds;
			end
			
			if( lastsecond ~= seconds ) then
				lastsecond = seconds
				clockframe = clockframe + 1
				
				if( clockframe >= 60 ) then
					clockframe = 1;
				end
				--clockHand:SetFrame( clockframe )
			end

			self.m_oSecondsText:SetText( secondsStr )
			
			if ( self.Relaxed == false ) then
				if (instance.flashTime > 0) then
					if (math.mod(instance.flashTime, 20) <= 10)  then
						self.m_oMinutesText:SetColor( 0xff0000 )
						self.m_oSecondsText:SetColor( 0xff0000 )
					else
						self.m_oMinutesText:SetColor( 0x0A323C )
						self.m_oSecondsText:SetColor( 0x0A323C )
					end
					instance.flashTime = self.flashTime - 1
				else
					self.m_oMinutesText:SetColor( 0x0A323C )
					self.m_oSecondsText:SetColor( 0x0A323C )
				end
			end
			
			instance:updateUI( )
		
		end

	end
	
	
	function instance:updateUI( )
		
		local mX =  GetMouseX() 
		local mY =  GetMouseY() 

			
		for i in pairs( instance.internalList ) do
			local item = instance.internalList[i]
			
			local listItem = instance.list[ "findList"..(i-1) ]
			
			if(item.needPopup == true) then
				--log("SetText " .. item.string .. " " .. item.sPopup)
				local text = listItem["text"]
				local popup = listItem["popup"]
				
				local fMouseX = listItem:GlobalToLocalX( mX )
				local fMouseY = listItem:GlobalToLocalY( mY )
							
				if(fMouseX >= listItem:GetX()
					and fMouseX <= text:GetX() + text:GetWidth()
					and fMouseY >= text:GetY()
					and fMouseY <= text:GetY() + 14 -- text:GetHeight()
					) 
				then
					popup:SetVisible(true)
				else	
					popup:SetVisible(false)
				end
				
				popup["text"]:SetColor( 0x042c50 )
				popup["text"]:SetText(item.sPopup)
			end
			
			
			
			local iColor = 0x042c50
			if ( listItem ~= nil ) then
				if( item.status == true ) then
					listItem:SetFrame( 1 )
					iColor = 0x7792ae --0x042c50
				else
					listItem:SetFrame( 0 )
					if ( item.super == false ) then
						iColor = 0x042c50
					else
						iColor = 0x0000ff
					end
				end
				
				listItem.text:SetColor( iColor )
				--log("SetText " .. item.string)
				listItem.text:SetText( item.string )
				
			end
		end
		
		if( instance.hintcount <= 0 ) then
			hintbutton:Disable()
--			if( cupid.cupid.arrow:GetVisible( ) == true ) then
--				cupid.cupid.arrow:SetVisible( false );		
--			end
		else
			hintbutton:Enable()
--			if( cupid.cupid.arrow:GetVisible( ) == false ) then
--				cupid.cupid.arrow:SetVisible( true );	
--			end
		end
	
		if ( self.m_bLockHintCounter == false ) then
			self.m_oHintCounterText:SetFrame( tonumber( instance.vishintcount ) )
		end
		
		itemCount:SetText( "" .. instance.totalItems )
		
	end
	
	function instance:HintHint( )	
		if( instance.hintcount > 0 
				and self.m_oHintButton._buttonGlint ~= nil ) then
			-- a slower version of the glint (so that the user sees it!)
			local oIrp = self:CreateIrp( 0, self.m_oHintButton._buttonGlint:GetNumFrames() - 1, 2, CIrpFuncs.mLinear, 0.75 )
			oIrp.m_oHookContext = self.m_oHintButton

			oIrp.mOnChange = function( i_oIrp, i_oContext )
				if ( i_oContext._buttonGlint ~= nil ) then
					i_oContext._buttonGlint:SetFrame( math.floor( i_oIrp:GetVal() ) )
				end
			end

			oIrp.mOnComplete = function( i_oIrp, i_oContext )
				if ( i_oContext._buttonGlint ~= nil ) then
					i_oContext._buttonGlint:SetFrame( 0 )
				end
			end
			
--			local hintie = cupid.cupid.arrow
--			hintie:CreateParticleEffect( "hinthint", "", hintie:GetWidth()/2, hintie:GetHeight()/2 )
		end
	end
end

if ( g_bReloading == nil or g_bReloading == false ) then
	ISpyPanel:Create( )
end
