local I = {}

-- Widgets used in the interface
local selectedStoreCategory, toolsCategoryButton, armsCategoryButton, armorCategoryButton, consumablesCategoryButton, miscCategoryButton
local noItemsOwnedLabel

local switchToCategory = function(category)

	selectedStoreCategory = category
	I.storeTable.reloadData()

end

-- Adjust category button sprites to reflect the current selection
local adjustCategoryButtons = function()

	print("adjustCategoryButtons")

	-- Unselected state by default
	toolsCategoryButton.setImage(gSpriteManager.getSprite(22, SpriteGroup.Town))
	armsCategoryButton.setImage(gSpriteManager.getSprite(24, SpriteGroup.Town))
	armorCategoryButton.setImage(gSpriteManager.getSprite(81, SpriteGroup.Town))
	consumablesCategoryButton.setImage(gSpriteManager.getSprite(36, SpriteGroup.Town))
	miscCategoryButton.setImage(gSpriteManager.getSprite(38, SpriteGroup.Town))

	-- Choose the selected image when correct category is selected
	if selectedStoreCategory == ItemCategory.Tool then
		toolsCategoryButton.setImage(gSpriteManager.getSprite(21, SpriteGroup.Town))
	elseif selectedStoreCategory == ItemCategory.Weapon then
		armsCategoryButton.setImage(gSpriteManager.getSprite(23, SpriteGroup.Town))
	elseif selectedStoreCategory == ItemCategory.Armor then
		armorCategoryButton.setImage(gSpriteManager.getSprite(80, SpriteGroup.Town))
	elseif selectedStoreCategory == ItemCategory.Consumable then
		consumablesCategoryButton.setImage(gSpriteManager.getSprite(35, SpriteGroup.Town))
	elseif selectedStoreCategory == ItemCategory.Other then
		miscCategoryButton.setImage(gSpriteManager.getSprite(37, SpriteGroup.Town))
	end

end

function I.create (contentType)

	I.window = LuaWindow(gGUI.createWindow({
		width = 250,
		height = 235,
		verticalAlignment = VerticalAlignment.Middle,
		id = "storeWnd",
		title = "%menu_town_store"
	}))


	-- Category buttons

	toolsCategoryButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = 15,
		y = 25,
		width = 41,
		height = 32,
		id = "storeCatTools",
		image = gSpriteManager.getSprite(21, SpriteGroup.Town)
	}))

	armsCategoryButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = toolsCategoryButton.getX() + 44,
		y = 25,
		width = 41,
		height = 32,
		id = "storeCatWeap",
		image = gSpriteManager.getSprite(21, SpriteGroup.Town)
	}))

	armorCategoryButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = armsCategoryButton.getX() + 44,
		y = 25,
		width = 41,
		height = 32,
		id = "storeCatArmor",
		image = gSpriteManager.getSprite(21, SpriteGroup.Town)
	}))

	consumablesCategoryButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = armorCategoryButton.getX() + 44,
		y = 25,
		width = 41,
		height = 32,
		id = "storeCatCons",
		image = gSpriteManager.getSprite(21, SpriteGroup.Town)
	}))

	miscCategoryButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = consumablesCategoryButton.getX() + 44,
		y = 25,
		width = 41,
		height = 32,
		id = "storeCatMisc",
		image = gSpriteManager.getSprite(21, SpriteGroup.Town)
	}))

	noItemsOwnedLabel = LuaText(gGUI.createText({
		parent = I.window.instance(),
		x = 30,
		y = 130,
		width = I.window.getWidth() - 60,
		height = 20,
		horizontalAlign = HorizontalAlignment.Center,
		text = "You don't own any items of this category",
		fontIndex = 0,
		colorIndex = 2
	}))


	-- Window action buttons

	if contentType == "buy" then

		local buyButton = LuaButton(gGUI.createButton({
			parent = I.window.instance(),
			x = 106,
			y = 222,
			width = 122,
			height = 18,
			id = "storeBuyBtn",
			title = "%buy_button"
		}))

		buyButton.onClick(function()
			Town.showTransactionWindow("buy")
		end)

	else

		local sellButton = LuaButton(gGUI.createButton({
			parent = I.window.instance(),
			x = 106,
			y = 222,
			width = 122,
			height = 18,
			id = "storeSellBtn",
			title = "%sell_button"
		}))

		sellButton.onClick(function()
			Town.showTransactionWindow("sell")
		end)


	end

	local doneButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = 20,
		y = 222,
		width = 80,
		height = 18,
		title = "%done_button"
	}))


	-- Table headers

	local tableHeaderName = LuaText(gGUI.createText({
		parent = I.window.instance(),
		x = 11,
		y = 66,
		width = 50,
		height = 10,
		font = 5,
		color = 2,
		text = "%store_table_item"
	}))

	local tableHeaderPossession = LuaText(gGUI.createText({
		parent = I.window.instance(),
		x = 96,
		y = 66,
		width = 60,
		height = 10,
		font = 5,
		color = 2,
		text = "%store_table_possession",
		horizontalAlign = HorizontalAlignment.Right
	}))

	local tableHeaderInStock = LuaText(gGUI.createText({
		parent = I.window.instance(),
		x = 140,
		y = 66,
		width = 50,
		height = 10,
		font = 5,
		color = 2,
		text = "%store_table_in_stock"
	}))

	local tableHeaderPrice = LuaText(gGUI.createText({
		parent = I.window.instance(),
		x = 178,
		y = 66,
		width = 48,
		height = 10,
		font = 5,
		color = 2,
		text = "%store_table_cost",
		horizontalAlign = HorizontalAlignment.Right
	}))

	-- Dynamic adjustments for some of the labels
	-- tableHeaderPossession.setX(140 - tableHeaderPossession.getTextBoundsForLine().x)
	tableHeaderInStock.setX(187 - (tableHeaderInStock.getTextBoundsForLine().x / 2))


	-- Item table

	I.storeTable = LuaTable(gGUI.createTable({
		parent = I.window.instance(),
		x = 8,
		y = 76,
		visibleRows = 8,
		rowHeight = 16,
		id = "storeTable"
	}))

	-- 231
	I.storeTable.addColumn(112)
	I.storeTable.addColumn(38)
	I.storeTable.addColumn(34)
	I.storeTable.addColumn(35)
	I.storeTable.addColumn(12)


	-- Bind callbacks

	doneButton.onClick(function()
		gGUI.scheduleForDeletion(I.window.instance())
		UI.Interfaces["supplyStore"] = nil
		I = nil
	end)

	toolsCategoryButton.onClick(function()
		switchToCategory(ItemCategory.Tool)
	end)

	armsCategoryButton.onClick(function()
		switchToCategory(ItemCategory.Weapon)
	end)

	armorCategoryButton.onClick(function()
		switchToCategory(ItemCategory.Armor)
	end)

	consumablesCategoryButton.onClick(function()
		switchToCategory(ItemCategory.Consumable)
	end)

	miscCategoryButton.onClick(function()
		switchToCategory(ItemCategory.Other)
	end)

	I.storeTable.onReloadData(function()

		print("I.storeTable.onReloadData")

		if selectedStoreCategory == nil then
			selectedStoreCategory = ItemCategory.Tool
		end

		I.storeTable.removeAllRows()

		local rowsAdded = 0

		for i=1, #Town.stock[1] do

			local stockItem = Town.stock[1][i]
			local itemDefinition = stockItem.item;
			local amountOwned = gTownState.countSupplyTypeTotal({primary = itemDefinition.index})

			local addRow = true

			if contentType == "buy" and stockItem.amount == 0 then
				addRow = false
			elseif contentType == "sell" and amountOwned == 0 then
				addRow = false
			end


			-- and stockItem.amount > 0 and itemDefinition:category(ItemCategory.Resource) == false

			if addRow == true and itemDefinition:category(selectedStoreCategory) == true and itemDefinition:category(ItemCategory.Resource) == false then

				-- Item title
				I.storeTable.addItemIVal({
					column = 0,
					text = gUtils.translate(itemDefinition.name),
					icon = gSpriteManager.getSprite(itemDefinition.index, SpriteGroup.Inventory),
					value = i
				})

				-- Amount owned
				I.storeTable.addItemIVal({
					column = 1,
					text = amountOwned,
					textAlignment = HorizontalAlignment.Right
				})

				-- Amount in stock
				I.storeTable.addItemIVal({
					column = 2,
					text = __ternary(stockItem.amount == 9999, "$", stockItem.amount),
					textAlignment = HorizontalAlignment.Right
				})

				-- Cost
				I.storeTable.addItemIVal({
					column = 3,
					text = stockItem.cost,
					textAlignment = HorizontalAlignment.Right
				})

				-- Empty padding at the end
				I.storeTable.addItem({
					column = 4,
					text = ""
				})

				rowsAdded = rowsAdded + 1

			end

		end

		adjustCategoryButtons()

		if I.storeTable.getSelectedRow() < 0 then
			I.storeTable.setSelectedRow(0)
		end

		if contentType == "sell" then
			if rowsAdded == 0 then
				noItemsOwnedLabel.setIsVisible(true)
			else
				noItemsOwnedLabel.setIsVisible(false)
			end
		elseif contentType == "buy" then
			noItemsOwnedLabel.setIsVisible(false)
		end

	end)

	I.storeTable.reloadData()

end

function I.getSelectedStockItem ()

	local column = LuaList(I.storeTable.getColumn(0))
	local dataSource = LuaListDataSource(column.getDataSource())

	print(I.storeTable.getSelectedRow(), dataSource.countItems())

	if I.storeTable.getSelectedRow() < 0 or I.storeTable.getSelectedRow() >= dataSource.countItems() then
		return nil
	end

	local dataItem = LuaListDataItem(dataSource.getItemAtIndex(I.storeTable.getSelectedRow()))

	return Town.stock[1][dataItem.iValue1()]
end

UI.Interfaces["supplyStore"] = I
