local I = {}

print("Start loading interface file ...")

local transactionStockItem, transactionItemDefinition, transactionType, maximumTransactionAmount, transactionAmount
local treasureAmountLabel, priceAmountLabel, totalCostAmountLabel, transactionAmountLabel

local close = function()

	gGUI.scheduleForDeletion(I.window.instance())
	UI.Interfaces["supplyStoreTransaction"] = nil
	I = nil

	-- Update store table
	if UI.Interfaces["supplyStore"] ~= nil then
		UI.Interfaces["supplyStore"].storeTable.reloadData()
	end
end

local calculateTotalPrice = function()
	local totalPrice = transactionStockItem.cost * transactionAmount
	if transactionType == "sell" then
		totalPrice = totalPrice * 0.8
	end
	return totalPrice
end

local completeTransaction = function()

	local totalPrice = calculateTotalPrice()

	-- Whadda ya buyin'
	if transactionType == "buy" then
		if totalPrice <= gParty.getTreasure() then
			gParty.decreaseTreasure(totalPrice)
			if transactionStockItem.amount ~= 9999 then
				transactionStockItem.amount = transactionStockItem.amount - transactionAmount
			end
			Town.addSupply(transactionItemDefinition, transactionAmount)
			close()
		else
			gGUI.showInfoMessage({key = "not_enough_gold"})
		end

	-- Whadda ya sellin'
	else
		gParty.increaseTreasure(totalPrice)
		gParty.removeResource({primary = transactionItemDefinition.index, amount = transactionAmount})
		if transactionStockItem.amount ~= 9999 then
			transactionStockItem.amount = transactionStockItem.amount + transactionAmount
		end
		close()
	end

end

function I.create (contentType, stockItem)

	transactionStockItem = stockItem
	transactionType = contentType
	transactionAmount = 1
	transactionItemDefinition = stockItem.item

	I.window = LuaWindow(gGUI.createWindow({
		width = 185,
		height = 94,
		offsetY = 26,
		verticalAlignment = VerticalAlignment.Middle,
		id = "transactionWnd"
	}))

	local itemIconBackground = LuaImage(gGUI.createImage({
		parent = I.window.instance(),
		id = "itemBg",
		x = 11,
		y = 10,
		height = 25,
		width = 25,
		image = gSpriteManager.getSprite(163, SpriteGroup.GUI)
	}))

	local itemIcon = LuaImage(gGUI.createImage({
		parent = itemIconBackground.instance(),
		x = 1,
		y = 1,
		height = 25,
		width = 25,
		image = gSpriteManager.getSprite(transactionItemDefinition.index, SpriteGroup.Inventory)
	}))

	local itemNameLabel = LuaText(gGUI.createText({
		parent = I.window.instance(),
		text = gUtils.translate(transactionItemDefinition.name),
		font = 5,
		color = 3,
		x = 34,
		y = 10,
		width = 65,
		height = 11,
		textTransform = "uppercase"
	}))

	local itemAmountValueString

	if contentType == "buy" then
		maximumTransactionAmount = stockItem.amount
	else
		-- local playerTownSupplies = LuaInventory(townState:getSupplies(Town.getCurrentTownIndex()))
		maximumTransactionAmount = gTownState.countSupplyTypeTotal({primary = transactionItemDefinition.index})
	end


	if maximumTransactionAmount == 9999 then
		itemAmountValueString = gUtils.translate("unlimited_units")
	else
		local unitMeasurement = transactionItemDefinition:category(ItemCategory.Consumable)

		if contentType == "buy" then
			if unitMeasurement == true then
				itemAmountValueString = string.format("%d %s", maximumTransactionAmount, gUtils.translate("buying_stock_units"))
			else
				itemAmountValueString = string.format("%d %s", maximumTransactionAmount, gUtils.translate("buying_stock_pieces"))
			end
		else
			if unitMeasurement == true then
				itemAmountValueString = string.format("%d %s", maximumTransactionAmount, gUtils.translate("selling_owned_units"))
			else
				itemAmountValueString = string.format("%d %s", maximumTransactionAmount, gUtils.translate("selling_owned_pieces"))
			end
		end
	end

	local itemAmountLabel = LuaText(gGUI.createText({
		parent = I.window.instance(),
		text = itemAmountValueString,
		font = 5,
		color = 2,
		x = 34,
		y = 19,
		width = 65,
		height = 11
	}))

	local treasureIcon = LuaImage(gGUI.createImage({
		parent = I.window.instance(),
		id = "itemBg",
		x = 103,
		y = 7,
		height = 139,
		width = 122,
		image = gSpriteManager.getSprite(25, SpriteGroup.Town)
	}))

	local treasureLabel = LuaText(gGUI.createText({
		parent = I.window.instance(),
		text = "%treasure_label",
		font = 5,
		color = 3,
		x = 133,
		y = 10,
		width = 65,
		height = 11,
		textTransform = "uppercase"
	}))

	treasureAmountLabel = LuaText(gGUI.createText({
		parent = I.window.instance(),
		text = string.format("%d %s", gParty.getTreasure(), gUtils.translate("price_suffix_gold")),
		font = 5,
		color = 2,
		x = 133,
		y = 19,
		width = 65,
		height = 11
	}))

	local priceLabel = LuaText(gGUI.createText({
		parent = I.window.instance(),
		text = "%price_label",
		font = 5,
		color = 3,
		x = 11,
		y = 33,
		width = 65,
		height = 11,
		textTransform = "uppercase"
	}))

	priceAmountLabel = LuaText(gGUI.createText({
		parent = I.window.instance(),
		text = "45 GOLD",
		font = 5,
		color = 2,
		x = 11,
		y = 42,
		width = 65,
		height = 11
	}))

	local totalCostLabel = LuaText(gGUI.createText({
		parent = I.window.instance(),
		text = "%total_label",
		font = 5,
		color = 3,
		x = 11,
		y = 54,
		width = 65,
		height = 11,
		textTransform = "uppercase"
	}))

	totalCostAmountLabel = LuaText(gGUI.createText({
		parent = I.window.instance(),
		text = "245 GOLD",
		font = 5,
		color = 2,
		x = 11,
		y = 62,
		width = 65,
		height = 11,
		textTransform = "uppercase"
	}))

	local amountLabel = LuaText(gGUI.createText({
		parent = I.window.instance(),
		text = "%amount_label",
		font = 5,
		color = 3,
		x = 74,
		y = 45,
		width = 65,
		height = 11,
		textTransform = "uppercase"
	}))

	transactionAmountLabel = LuaText(gGUI.createText({
		parent = I.window.instance(),
		text = "10.0 UNITS",
		font = 5,
		color = 2,
		x = 74,
		y = 53,
		width = 65,
		height = 11,
		textTransform = "uppercase"
	}))

	local buttonSpeed = RepeatSpeed.Fast

	if transactionItemDefinition:category(ItemCategory.Consumable) then
		buttonSpeed = RepeatSpeed.VeryFast
	end

	local increaseButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = 125,
		y = 44,
		width = 20,
		height = 18,
		title = "+",
		clickRepeat = {enabled = true, speed = buttonSpeed}
	}))

	local decreaseButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = 149,
		y = 44,
		width = 20,
		height = 18,
		title = "-",
		clickRepeat = {enabled = true, speed = buttonSpeedt}
	}))





	local closeButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = (I.window.getWidth() / 2) - 75,
		y = I.window.getHeight() - 13,
		width = 72,
		height = 18,
		title = "%close_button"
	}))

	local confirmButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = (I.window.getWidth() / 2) + 3,
		y = I.window.getHeight() - 13,
		width = 72,
		height = 18,
		title = __ternary(contentType == "buy", "%buy_button", "%sell_button")
	}))


	-- Bindings

	closeButton.onClick(close)

	increaseButton.onClick(function()
		local step = 1
		--__ternary(transactionItemDefinition:category(ItemCategory.Consumable) == true, 0.5, 1)
		transactionAmount = math.min(transactionAmount + step, maximumTransactionAmount)
	end)

	decreaseButton.onClick(function()
		local step = 1
		--__ternary(transactionItemDefinition:category(ItemCategory.Consumable) == true, 0.5, 1)
		transactionAmount = math.max(transactionAmount - step, step)
	end)

	confirmButton.onClick(completeTransaction)

	priceAmountLabel.content(function()
		if transactionStockItem.cost > 0 then
			return string.format("%.1f %s", transactionStockItem.cost, gUtils.translate("price_suffix_gold"))
		else
			return gUtils.translate("cost_free")
		end
	end)

	totalCostAmountLabel.content(function()
		local totalPrice = calculateTotalPrice()
		if totalPrice > 0 then
			return string.format("%d %s", math.ceil(totalPrice), gUtils.translate("price_suffix_gold"))
		else
			return gUtils.translate("cost_none")
		end
	end)

	transactionAmountLabel.content(function()
		if transactionItemDefinition:category(ItemCategory.Consumable) == false then
			return string.format("%d %s", transactionAmount, gUtils.translate("format_suffix_pieces"))
		else
			return string.format("%d %s", transactionAmount, gUtils.translate("format_suffix_units"))
		end
	end)

end

print("Done!")

UI.Interfaces["supplyStoreTransaction"] = I
