#include "messages.lua"
#include "missions.lua"
#include "starthub.lua"

pEnabled = true

from = ""
message = ""
index = 0
totalMessages = 0
currentMessageId = ""
currentMessageIndex = 1

function init()
	playNotificationSound = false
	notificationInterval = 10
	notificationTimer = 0
	buzzCounter = 0

	hudNotification = "Check your cellphone for messages"
		
	newMessageSound = LoadSound("MOD/script/cellphone/sms-signal.ogg")
	buzzSound = LoadSound("MOD/script/cellphone/vibrate-short.ogg")

	currentMessageId = ""
	currentMessageIndex = 1

	receivedMessage = ""

	checkPhone("")
	showPhone = false
end

function tick(dt)
	
	playerVehicle = GetPlayerVehicle()
	alarm = GetBool("level.alarm")
	delivering = GetBool("level.delivering")

	if playNotificationSound and not alarm and not delivering and playerVehicle == 0 then
		notificationTimer = notificationTimer + dt
		if notificationTimer > notificationInterval then
			PlaySound(buzzSound)
			notificationTimer = 0
			buzzCounter = buzzCounter + 1
		end
		if buzzCounter >= 3 then
			SetString("hud.notification", hudNotification)
		end
	end
	newMessage = GetString("cellphone.newMessage")
	if newMessage ~= "" then
		receiveMessage(newMessage)
		SetString("cellphone.newMessage","")
	end

	if GetPlayerScreen() == UiGetScreen() and not showPhone then
		checkPhone("")
	end
	if showPhone and GetPlayerScreen() == UiGetScreen() and playNotificationSound and notificationTimer > 1 then
		--Receive message if phone is already active
		checkPhone("")
	end
	if showPhone and GetPlayerScreen() ~= UiGetScreen() then
		close()
	end
	if showPhone then
		SetBool("hud.disable", true)
	end
end

function receiveMessage(messageId)
	messageQue = GetString("savegame.mod.messageque")
	if isMessageReceived(messageId) then 
		messageIds = splitString(messageQue,",")
		index = indexOf(messageIds,messageId)
		if index ~= nil then
			table.remove(messageIds,index)
			clearedque = table.concat(messageIds,",")
			messageQue = clearedque
			SetString("savegame.mod.messageque",messageQue)
		end
	end

	receivedMessage = messageId
	playNotificationSound = true
	buzzCounter = 0
	
	PlaySound(buzzSound)
	PlaySound(newMessageSound)
	SetString("game.player.tool","cellphone")

	if messageQue == "" then
		messageQue = messageId	
	else
		messageQue = messageQue .. "," .. messageId	
	end
		
	SetString("savegame.mod.messageque", messageQue)

	SetInt("savegame.mod.message."..messageId, 1)
end

function checkPhone(messageId)
	showPhone = true
	playNotificationSound = false

	currentMessageId = messageId
	
	messageQue = GetString("savegame.mod.messageque")
	messageIds = splitString(messageQue,",")

	currentMessageIndex = #messageIds
	totalMessages = #messageIds

	if messageId == "" then 
		messageId = messageIds[currentMessageIndex]
		currentMessageId = messageId
	end

	if messageId then
		displayMessage(messageId)
	end
end

function displayMessage(messageId)
	from = gArtMessages[messageId].from
	message = gArtMessages[messageId].body
	index = indexOf(messageIds,messageId)
	if index == nil then
		index = 1
	end
	totalMessages = #messageIds
end

function isMessageReceived(messageId)
	return GetInt("savegame.mod.message."..messageId) > 0
end

function close()
	if receivedMessage ~= "" then
		SetInt("savegame.mod.message."..receivedMessage..".read", 1)
	end
	showPhone = false
end


function draw()
	UiFont("cellphone/pixeloid.ttf", 38)
	UiPush()
		drawPhone()
	UiPop()
	UiPush()
		UiColor(1,1,1,0.5)
		UiScale(2)
		UiImage("cellphone/raster.png")
	UiPop()
end


function drawPhone()
	UiPush()
		UiAlign("center middle")

		UiWordWrap(600)
		
		UiColorFilter(0.5, 1, 1)
		
		UiTranslate(20,20)
		UiPush()
			
			UiAlign("top left")
			UiPush()
				UiPush()
					UiTranslate(230, 4)
					if index == nil then
						index = 0
					end
					UiText("SMS "..index.."/"..totalMessages, true)
				UiPop()
				
				UiPush()
					UiButtonImageBox("ui/common/box-solid-6.png", 6, 6, 1, 1, 1)
					UiColor(0,0,0)
					UiTranslate(0, 0)
					UiPush()
						if currentMessageIndex - 1 <= 0 then
							UiDisableInput()
							UiColorFilter(1,1,1,0.5)
						end
						if UiTextButton("ÎÀÈÀÄ", 150, 40) then
							if currentMessageIndex - 1 > 0 then
								if receivedMessage ~= "" then
									SetInt("savegame.mod.message."..receivedMessage..".read", 1)
								end
								UiSound("cellphone/button-beep.ogg", 0.5)
								currentMessageIndex = currentMessageIndex - 1
								messageId = messageIds[currentMessageIndex]
								currentMessageId = messageId
								displayMessage(messageId)
							end
						end
					UiPop()
					UiTranslate(450, 0)
					UiPush()
						if currentMessageIndex + 1 > totalMessages then
							UiDisableInput()
							UiColorFilter(1,1,1,0.5)
						end
						if UiTextButton("ÂÐÅÑÅÄ", 150, 40) then
							if currentMessageIndex + 1 <= totalMessages then
								if receivedMessage ~= "" then
									SetInt("savegame.mod.message."..receivedMessage..".read", 1)
								end
								UiSound("cellphone/button-beep.ogg", 0.5)
								currentMessageIndex = currentMessageIndex + 1
								messageId = messageIds[currentMessageIndex]
								currentMessageId = messageId
								displayMessage(messageId)
							end
						end
					UiPop()
				UiPop()

			UiPop()
			
			UiTranslate(0, 80)
			if from ~= "" then
				UiText("Ïö: "..from)
			end

			UiTranslate(0, 70)
					
			if message == "" then
				message = "No messages"
			end
			UiText(message, true)

			UiTranslate(0, 20)

			UiPush()
				if currentMessageId then
					UiTranslate(20, 0)
					UiButtonImageBox("ui/common/box-solid-6.png", 6, 6, 1, 1, 1)
					UiColor(0,0,0)

					hasMission = gArtMessages[currentMessageId].mission

					--spcecial case to be able to replay paperboy mission
					if currentMessageId == "intro" and GetBool("savegame.mod.tutorial.complete") then
						hasMission = "paperboy"
					end
					if hasMission ~= "" then
						if not GetBool("savegame.mod."..hasMission..".complete") and GetBool("options.game.missionskipping") then
							if UiTextButton("SKIP MISSION", 260, 48) then
								UiSound("cellphone/button-beep.ogg", 0.5)
								skipMission(hasMission)
							end
						end
						UiTranslate(300, 0)
						UiPush()
							UiAlign("center middle")
							UiTranslate(130, 24)
							if not GetBool("savegame.mod."..hasMission..".complete") then
								UiScale(math.max(1.0, math.sin(GetTime()*4)*0.05+1.0))
							end
							if UiTextButton("ÎÀÚÀÓß", 260, 48) then
								UiSound("cellphone/button-beep.ogg", 0.5)
								startMission(hasMission)
							end
						UiPop()
					end
				end
			UiPop()
		UiPop()
		UiPush()
			UiTranslate(300, 590)
			UiButtonImageBox("ui/common/box-solid-6.png", 6, 6, 1, 1, 1)
			UiColor(0,0,0)
			if UiTextButton("ÈÀËÑÞÓß", 160, 40) then
				UiSound("cellphone/button-beep.ogg", 0.5, 1.2)
				SetPlayerScreen(0)
			end
		UiPop()
		UiPush()	
			UiTranslate(40, 600)
			UiFont("regular.ttf", 24)
			UiColor(1,1,1,0.7)
			
			--if UiTextButton("debug reset", 200, 36) then
			--	resetProgress()
			--end
			
		UiPop()
	UiPop()
	if playNotificationSound then	
		UiColor(0,0,0,0.5)
		UiRect(UiWidth(), UiHeight())
		UiColor(1,1,1)
		if math.mod(GetTime(), 0.8) > 0.3 then
			UiPush()
				UiColorFilter(0.5, 1, 1)
				UiAlign("center middle")
				UiTranslate(UiCenter(), UiMiddle())
				UiImageBox("ui/common/box-solid-6.png", 500, 120, 6, 6)
				UiWindow(400, 100)
				UiTranslate(UiCenter(), UiMiddle())
				UiScale(1.5)
				UiColorFilter(0, 0, 0)
				UiText("ÎÏÂÏÅ ÒÏÏÁÜÅÎÉÅ")		
			UiPop()
		end
	end	
end

function splitString(str, delimiter)
	local result = {}
	for word in string.gmatch(str, '([^'..delimiter..']+)') do
		result[#result+1] = trim(word)
	end
	return result
end

function indexOf(array, value)
    for i, v in ipairs(array) do
        if v == value then
            return i
        end
    end
    return nil
end

function trim(s)
   return (s:gsub("^%s*(.-)%s*$", "%1"))
end

function startMission(id)
	if receivedMessage ~= "" then
		SetInt("savegame.mod.message."..receivedMessage..".read", 1)
	end
	StartLevel(id, gArtMissions[id].file, gArtMissions[id].layers)
end

function skipMission(id)
	if receivedMessage ~= "" then
		SetInt("savegame.mod.message."..receivedMessage..".read", 1)
	end
	SetBool("savegame.mod."..id..".complete",true)

	startHub()
end


function resetProgress()
	DebugPrint("Tutorial progress was reset")
	SetBool("savegame.mod.tutorial.complete",false)
	SetBool("savegame.mod.tutorial.car",false)

	DebugPrint("Mission progress was reset")
	SetBool("savegame.mod.paperboy.complete",false)
	SetBool("savegame.mod.art_heist.complete",false)
	SetBool("savegame.mod.museum_heist.complete",false)
	SetBool("savegame.mod.art_calm.complete",false)
	SetBool("savegame.mod.museum_destroy.complete",false)

	DebugPrint("MOD savegame was reset")
	ClearKey("savegame.mod")
	ClearKey("level.track")
	ClearKey("cellphone")
end
