DialogManager = {}
DialogManager.Dialogs = {}
DialogManager.CurrentDialogKey = nil
DialogManager.CurrentDialogTreeKey = nil
DialogManager.CurrentDialogIndex = 0

local localizations = {}

local UI_created = false
local animationProgress = 0

function createUI()
	UI_created = true
	print("Create UI")
	gGUI.loadScriptedInterface("dialog_content", true)
	gGUI.loadScriptedInterface("dialog_options", true)
	gGUI.loadScriptedInterface("dialog_title", true)
end

function DialogManager.currentDialog ()
	return DialogManager.Dialogs[DialogManager.CurrentDialogKey]
end

function DialogManager.currentDialogTree ()

	print("Return dialog tree "..DialogManager.CurrentDialogTreeKey.." for dialog "..DialogManager.CurrentDialogKey)
	print(DialogManager.Dialogs[DialogManager.CurrentDialogKey])
	print(DialogManager.Dialogs[DialogManager.CurrentDialogKey].DialogTrees)
    print(DialogManager.Dialogs[DialogManager.CurrentDialogKey].DialogTrees[DialogManager.CurrentDialogTreeKey])

	return DialogManager.Dialogs[DialogManager.CurrentDialogKey].DialogTrees[DialogManager.CurrentDialogTreeKey]
end

function DialogManager.setDialogAvailable (dialogKey, available)
	gVarStore.setBool(dialogKey.."_avail", available)
end

function DialogManager.isDialogAvailable (dialogKey)
	if DialogManager.Dialogs[dialogKey] == nil then
		return false
	end
	return gVarStore.getBool(dialogKey.."_avail")
end

function DialogManager.isDialogTreeOpened (dialogTreeKey, dialogKey)
	-- no dialog key is provided, assume current dialog
	if dialogKey == nil then
		dialogKey = DialogManager.CurrentDialogKey
	end

	return gVarStore.getBool(dialogKey.."_"..dialogTreeKey)
end

function DialogManager.startDialogTree (dialogTreeKey)
	DialogManager.CurrentDialogIndex = 0
	DialogManager.CurrentDialogTreeKey = dialogTreeKey
	DialogManager.currentDialogTree().started()
end

function DialogManager.resetDialogTree (dialogKey, dialogTreeKey)
	gVarStore.setBool(dialogKey.."_"..dialogTreeKey, false)
end

function DialogManager.endCurrentDialogTree ()
	print("endCurrentDialogTree")
	UI.Interfaces["dialog_content"].window.hide()
	gVarStore.setBool(DialogManager.CurrentDialogKey.."_"..DialogManager.CurrentDialogTreeKey, true)
	DialogManager.currentDialogTree().ended()
	DialogManager.CurrentDialogTreeKey = nil
	DialogManager.populateContentForCurrentKey()
	LuaSound(gSoundManager.getSound(22, SoundGroup.SFX)).stop()
end

function DialogManager.showDialog (args)
	UI.Interfaces["dialog_content"].window.show()
	UI.Interfaces["dialog_content"].display(DialogManager.translate(args.key))
	UI.Interfaces["dialog_options"].fillList(args.options)
end

function DialogManager.dismissDialog (dialogIndex, dialogIdentifier)
	DialogManager.currentDialogTree().dismiss(dialogIndex, dialogIdentifier)
end

function DialogManager.translate (key, dialogKey)
	-- no dialog key is provided, assume current dialog
	if dialogKey == nil then
		dialogKey = DialogManager.CurrentDialogKey
	end
	return localizations[dialogKey]:getTranslation(key)
end

function DialogManager.populateContentForCurrentKey ()
	-- print("populateContentForCurrentKey = ", DialogManager.CurrentDialogKey)
	UI.Interfaces["dialog_title"].updateTitle()
	UI.Interfaces["dialog_options"].fillList()
end

function DialogManager.loadDialogs (dialogs)
	for i = 1, #dialogs do
		gLuaHandler.loadFile(dialogs[i][2].."/main.lua")
		DialogManager.Dialogs[dialogs[i][1]].DialogTrees = {}
		gLuaHandler.loadDirectory(dialogs[i][2].."/dialogtrees")
		localizations[dialogs[i][1]] = LuaLocalization(gGame.readLocalizationFile("en", "dialogs/"..dialogs[i][1].."/localization"))
	end
end

function DialogManager.close ()
	gGUI.doScreenTransition({
		type = Transition.DitherOut,
		callbackId = gUtils.hash("end_dialog")
	})
end

function DialogManager.showChangeDialogWindow ()
	print("showChangeDialogWindow")
	if UI.Interfaces["change_dialog"] == nil then
		gGUI.loadScriptedInterface("change_dialog", true)
		UI.Interfaces["change_dialog"].fillList()
	end
end

function DialogManager.listAllAvailableDialogs ()
	local dialogs = {};
	for k, v in pairs(DialogManager.Dialogs) do
		if DialogManager.Dialogs[k].isAvailable() then
			print("add")
			table.insert(dialogs, k)
		end
	end
	return dialogs;
end

function DialogManager.newDialogTopicsAvailable (dialogKey)
	local topics = DialogManager.Dialogs[dialogKey].getTopics()
	for i = 1, #topics do
		if DialogManager.isDialogTreeOpened(topics[i], dialogKey) == false then
			return true
		end
	end
	return false
end

function DialogManager.changeDialog (newDialogKey)
	DialogManager.CurrentDialogKey = newDialogKey
	UI.Interfaces["dialog_title"].updateTitle()
	UI.Interfaces["dialog_options"].fillList()
end

function DialogManager.onInit (param)

	print("DialogManager.onInit() ... ", UI_created)
	print(param)

	animationProgress = 0.85

	if UI_created == false then
		createUI()
	end

	UI.Interfaces["dialog_content"].window.hide()
	UI.Interfaces["dialog_options"].window.hide()

	DialogManager.populateContentForCurrentKey()

end

function DialogManager.onUpdate (frameTime)

	local screenSize = gGUI.getScreenSize(true) -- scaled screen size
	local optionsWindow = UI.Interfaces["dialog_options"].window
	local contentWindow = UI.Interfaces["dialog_content"].window
	local titleContainer = UI.Interfaces["dialog_title"].container

	titleContainer.setX(screenSize.x / 2)
  titleContainer.setY(30)

	contentWindow.setX((screenSize.x - contentWindow.getWidth()) / 2)
    contentWindow.setY(screenSize.y / 2 - 105)

	optionsWindow.setX((screenSize.x - optionsWindow.getWidth()) / 2)
	optionsWindow.setY(screenSize.y / 2 + 24)

	if animationProgress > 0.0 then
		animationProgress = animationProgress - frameTime
		if animationProgress < 0.0 then
			animationProgress = 0.0
			UI.Interfaces["dialog_options"].window.show()
		end
	end

end

function DialogManager.onDraw ()

	local screenSize = gGUI.getScreenSize()

	-- Fill background
	gGame.fillRect({
		width = screenSize.x,
		height = screenSize.y,
		colorIndex = 0
	})

	local leftShapeSprite = gSpriteManager.getSprite(0, SpriteGroup.DialogScreen)
	local rightShapeSprite = gSpriteManager.getSprite(1, SpriteGroup.DialogScreen)

	local shapeX = ((screenSize.x - gUtils.scale(460)) / 2) - gUtils.scale(90 * animationProgress)

	gGame.drawSprite(leftShapeSprite, {x = shapeX, y = screenSize.y})
	gGame.drawSprite(rightShapeSprite, {x = screenSize.x - shapeX, y = screenSize.y})


	local topBorderSprite = gSpriteManager.getSprite(152, SpriteGroup.GUI)
	local bottomBorderSprite = gSpriteManager.getSprite(153, SpriteGroup.GUI)

	local xIncrease = gUtils.scale(431)

	for x = 0, screenSize.x, xIncrease do
		gGame.drawSprite(topBorderSprite, {x = x, y = 0})
		gGame.drawSprite(bottomBorderSprite, {x = x, y = screenSize.y})
	end

end

function DialogManager.onClear ()
	-- UI.Interfaces["dialog_options"] = nil
	-- UI.Interfaces["dialog_content"] = nil

	if UI.Interfaces["change_dialog"] ~= nil then
		UI.Interfaces["change_dialog"].close()
	end

	DialogManager.CurrentDialogTreeKey = nil
	DialogManager.CurrentDialogKey = nil

	LuaSound(gSoundManager.getSound(22, SoundGroup.SFX)).stop()
end

function DialogManager.onEventSystem (args)

	if gGame.getState() ~= GameState.Dialog then
		return
	end

	--print("dlg mngr sys event")
end

function DialogManager.onEventGUI (args)

	if gGame.getState() ~= GameState.Dialog then
		return
	end

	UI.Interfaces["dialog_options"].onEventGUI(args)

	if UI.Interfaces["change_dialog"] ~= nil then
		UI.Interfaces["change_dialog"].onEventGUI(args)
	end

	print("dlg mngr gui event")
end

gLuaHandler.registerDelegateCallbacks(DialogManager, Delegates.EventsGUI, 0, DialogManager.onEventGUI)
gLuaHandler.registerDelegateCallbacks(DialogManager, Delegates.EventsSystem, 0, DialogManager.onEventSystem)

DialogManager.loadDialogs({

	{"captainbarlow", "dialogs/captainbarlow"},

	{"tavernkeeper0", "dialogs/tavernkeeper0"},
	{"merchant0", "dialogs/merchant0"},
	{"harbormaster0", "dialogs/harbormaster0"},

	{"tavernkeeper1", "dialogs/tavernkeeper1"},
	{"provisioner", "dialogs/provisioner"},

	{"tavernkeeper2", "dialogs/tavernkeeper2"},
	{"merchant2", "dialogs/merchant2"},
	{"harbormaster2", "dialogs/harbormaster2"},
})
