local D = {}

function D.show (index)

	DialogManager.CurrentDialogIndex = index

	if index == 1 then
		DialogManager.showDialog({key = "ale_response_1", options = {{key = "continue", id = ConstEndDialog}}})
	elseif index == 2 then
		DialogManager.showDialog({key = "ale_response_2", options = {{key = "continue", id = ConstEndDialog}}})
	end
end

-- Called when choosing an reply option from the list
function D.dismiss (index, identifier)

	-- Reply that indicates to end the dialog tree
	if identifier == ConstEndDialog then
		DialogManager.endCurrentDialogTree()
		return
	end

	D.show(DialogManager.CurrentDialogIndex + 1)

end

-- Called when dialog tree is initialized
function D.started ()

	local msgBody = DialogManager.translate("message_box_ale_content")
	local msgTitle = DialogManager.translate("message_box_ale_title")

	gGUI.showMessageBox({
		text = msgBody,
		title = msgTitle,
		type = MessageBoxType.Confirmation,
		id = 1234,
		verticalAlign = VerticalAlignment.Middle
	})

end

-- Called when dialog tree is terminated
function D.ended ()
	if gVarStore.getInt("ales_bought") == 1 then
		DialogManager.resetDialogTree("harbormaster2", "buy_ale")
	end
end

function D.messageBoxDismissed(args)

	if args.id == 1234 then
		-- Yes
		if args.button == 2 then
			gParty.decreaseTreasure(2)
			gVarStore.setInt("ales_bought", gVarStore.getInt("ales_bought") + 1)

			if gVarStore.getInt("ales_bought") == 2 then
				DialogManager.resetDialogTree("harbormaster2", "ask_travel")
			end

			D.show(1)
		elseif args.button == 1 then
			DialogManager.endCurrentDialogTree()
		end
	end


	--[[local ctx = LuaDialogContext(dialog:getContext("harbormaster2"));
	if id == 1234 then
		-- Yes
		if button == 2 then
			print("Yes button clicked")
			party:decreaseTreasure(2)
			ctx:setInteger(0, ctx:getInteger(0) + 1)
			print("integer[0] = ", ctx:getInteger(0))
			if ctx:getInteger(0) == 1 then
				showDialog(0)
			else
				showDialog(1)
			end
			return true
		--No
		elseif button == 1 then
			print("No button clicked")
			dialog:callEnd()
		end
	end]]--
	return false
end

gLuaHandler.registerDelegateCallbacks(D, Delegates.MessageBox, 0, D.messageBoxDismissed)

-- Register globally
DialogManager.Dialogs["harbormaster2"].DialogTrees["buy_ale"] = D
