startFarmScreen = {}
startFarmScreen.VehicleListToElementMap = {}

local startFarmScreen_mt = Class(startFarmScreen, ScreenElement)
--local startFarmScreen_mt = Class(startFarmScreen, TabbedMenu)

startFarmScreen.CONTROLS = {

	TITLE = "title",
	FARM_ID = "farm_id",
	FARM_HEADER = "farmHeader",
	MONEY = "money",
	DESCRIPTION = "description",
	BUTTON = "buttonOK",
	PIC1 = "pic1",
	PIC2 = "pic2",
	YARD = "yardSize",
	FARM_SIZE = "farmSize",
	TOTAL = "totalSize",
	HEADERBOX = "tableHeaderBox",
	TABLE = "vehicleTable",
	-- TABLE_TEMPLATE = "vehicleRowTemplate"
}



function startFarmScreen:new()
	local self = ScreenElement.new(nil, startFarmScreen_mt)

	self:registerControls(startFarmScreen.CONTROLS)

	return self
end

function startFarmScreen:onGuiSetupFinished()
	startFarmScreen:superClass().onGuiSetupFinished(self)
	self.vehicleTable:setDataSource(self)
end

function startFarmScreen:onOpen()
	startFarmScreen:superClass().onOpen(self)


	local farmIDs = {}
	for i = 1, #RDM_StartFarm.startFarms do
		table.insert(farmIDs, tostring(i))
	end

	self.farm_id:setTexts(farmIDs)

	self.farm_id:setState(1, true)

	-- Disable sounds, focus on the Farm option element and re-enable sounds
	-- (Disabling click sounds when calling setFocus())
	self:setSoundSuppressed(true)
	FocusManager:setFocus(self.farm_id)
	self:setSoundSuppressed(false)
end

function startFarmScreen:onSelectFarm()
	local selection = self.farm_id:getState()
	RDM_StartFarm.pickedFarm = selection
	RDM_StartFarm:setStartFarmSelection()
	g_gui:showGui("")
end

function startFarmScreen:onClose()
	startFarmScreen:superClass().onClose(self)
end

function startFarmScreen:onFarmSelectChange()
	local selection = self.farm_id:getState()


	local moneyValue = g_i18n:formatMoney(RDM_StartFarm.startFarms[selection].money)
	local descriptionValue = "$l10n_" .. RDM_StartFarm.startFarms[selection].description
	descriptionValue = startFarmScreen:getText(descriptionValue)

	local headerValue = RDM_StartFarm.startFarms[selection].header
	headerValue = startFarmScreen:getText(headerValue)


	local pica = RDM_StartFarm.MapModDir .. RDM_StartFarm.startFarms[selection].imageA
	local picb = RDM_StartFarm.MapModDir .. RDM_StartFarm.startFarms[selection].imageB

	if not fileExists(pica) then
		pica = RDM_StartFarm.ModDir .. "placeholder.dds"
	end
	if not fileExists(picb) then
		picb = RDM_StartFarm.ModDir .. "placeholder.dds"
	end

	local yardValue = 0
	local sizeValue = 0
	local totalValue = 0

	yardValue = string.format("%.2f ", startFarmScreen:getSize(selection, "yard"))
	sizeValue = string.format("%.2f ", startFarmScreen:getSize(selection, "farm"))
	local v = startFarmScreen:getValue(selection, "yard")
	yardValue = yardValue .. " / " .. tostring(g_i18n:formatMoney(v))
	totalValue = v
	v = startFarmScreen:getValue(selection, "farm")
	totalValue = totalValue + v
	sizeValue = sizeValue .. " / " .. tostring(g_i18n:formatMoney(v))

	self.yardSize:setText(yardValue)
	self.farmSize:setText(sizeValue)
	self.totalSize:setText(g_i18n:formatMoney(totalValue))


	--Test self.pic1:setImageFilename(pica)





	self.pic2:setImageFilename(picb)
	self.money:setText(moneyValue)
	self.description:setText(descriptionValue)
	self.farmHeader:setText(headerValue)

	-- First we populate self.vehicleList
	self:buildVehicleList(selection)

	-- Then we tell the SmoothList to clear and rebuild
	self.vehicleTable:reloadData()
end

function startFarmScreen:getSize(farmID, selector)
	local size = 0
	local farmlands = {}
	if selector == "yard" then
		table.insert(farmlands, RDM_StartFarm.startFarms[farmID].farmlands[1])
	else
		for k, v in pairs(RDM_StartFarm.startFarms[farmID].farmlands) do
			if k > 1 then
				table.insert(farmlands, v)
			end
		end
	end

	for k, v in ipairs(farmlands) do
		local farmland = g_farmlandManager:getFarmlandById(v)
		size = size + farmland.areaInHa
	end
	return size
end

function startFarmScreen:getValue(farmID, selector)
	local value = 0

	local farmlands = {}
	if selector == "yard" then
		table.insert(farmlands, RDM_StartFarm.startFarms[farmID].farmlands[1])
	else
		for k, v in pairs(RDM_StartFarm.startFarms[farmID].farmlands) do
			if k > 1 then
				table.insert(farmlands, v)
			end
		end
	end

	for k, v in ipairs(farmlands) do
		local farmland = g_farmlandManager:getFarmlandById(v)
		value = value + farmland.price
	end
	return value
end

function startFarmScreen:getText(textName)
	if textName ~= nil then
		local text = ""
		if textName:sub(1, 6) == "$l10n_" then
			local subText = textName:sub(7)
			if g_i18n:hasText(subText, RDM_StartFarm.MapMod) then
				text = g_i18n:getText(subText, RDM_StartFarm.MapMod)
			end
		elseif g_i18n:hasText(textName, RDM_StartFarm.MapMod) then
			text = g_i18n:getText(textName, RDM_StartFarm.MapMod)
		end

		if text ~= "" then
			return text
		end


		-- If all fail's and there is no 'backup' we need to provide the default warning so texts are entered correctly by modders.
		return g_i18n:getText(textName)
	end

	return ""
end

function startFarmScreen:buildVehicleList(selection)
	-- Use this function to populate self.vehicleList with vehicle data

	--DebugUtil.printTableRecursively(self.vehicleTable,".",0,1)
	-- self.vehicleTable:deleteListItems()

	Logging.info('startFarmScreen:buildVehicleList()')

	-- Clear the vehicleList
	self.vehicleList = {}

	startFarmScreen.VehicleListToElementMap = {}
	local elementIndex = 1
	local group = ""
	if RDM_StartFarm.startFarms[selection].vehicleDetails ~= nil then
		for k, v in pairs(RDM_StartFarm.startFarms[selection].vehicleDetails) do
			table.insert(self.vehicleList, v)
			-- local row = self:createItem(v)
			-- startFarmScreen.VehicleListToElementMap[elementIndex] = k
			-- elementIndex = elementIndex + 1
		end
	else
		-- -- Lets put in some test data
		-- table.insert(self.vehicleList, {
			-- RDM_StartFarm.ModDir .. 'icon_RDM_StartFarmPicker.png',
			-- 'Ford 6600',
			-- '1.000€',
			-- '40'
		-- })
		-- table.insert(self.vehicleList, {
			-- RDM_StartFarm.ModDir .. 'icon_RDM_StartFarmPicker.png',
			-- 'Volvo T403',
			-- '88.000€',
			-- '140'
		-- })
		-- table.insert(self.vehicleList, {
			-- RDM_StartFarm.ModDir .. 'icon_RDM_StartFarmPicker.png',
			-- 'New Holland T550',
			-- '120.000€',
			-- '20'
		-- })
		-- table.insert(self.vehicleList, {
			-- RDM_StartFarm.ModDir .. 'icon_RDM_StartFarmPicker.png',
			-- 'Another fake entry #1',
			-- '120.000€',
			-- '20'
		-- })
		-- table.insert(self.vehicleList, {
			-- RDM_StartFarm.ModDir .. 'icon_RDM_StartFarmPicker.png',
			-- 'Another fake entry #2',
			-- '120.000€',
			-- '20'
		-- })
		-- table.insert(self.vehicleList, {
			-- RDM_StartFarm.ModDir .. 'icon_RDM_StartFarmPicker.png',
			-- 'Another fake entry #3',
			-- '120.000€',
			-- '20'
		-- })
	end
end

---Create a list item
-- function startFarmScreen:createItem(data)
-- 	DebugUtil.printTableRecursively(data, ".", 0, 0)
-- 	local item = self.vehicleRowTemplate:clone(self.vehicleTable)
-- 	--item:applyProfile("rd_AuctionListItem")
-- 	item:getDescendantByName("vecImage"):setImageFilename(data[1])
-- 	-- item:getDescendantByName("vecName"):setText(data[2])
-- 	-- item:getDescendantByName("vecPrice"):setText(data[3])
-- 	-- item:getDescendantByName("vecOperatingTime"):setText(data[4])


-- 	return item
-- end



-- This function will be called by SmoothList
-- Return the number of sections
-- Since we only have 1 section we just return 1
function startFarmScreen:getNumberOfSections(list)
	return 1
end

-- Return the number of vehicles we want to display in the list
function startFarmScreen:getNumberOfItemsInSection(list, section)
	return #self.vehicleList
end

-- This function will be called by SmoothList for each item shown
function startFarmScreen:populateCellForItemInSection(list, section, index, cell)
	local vehicle = self.vehicleList[index]

	if vehicle ~= nil then
		cell:getAttribute('vecImage'):setImageFilename(vehicle[1])
		cell:getAttribute('vecName'):setText(vehicle[2])
		--cell:getAttribute('vecPrice'):setText(vehicle[3])
		cell:getAttribute('vecOperatingTime'):setText(vehicle[4])
	else
		cell:getAttribute('vecName'):setText('vehicle is nil')
	end
end
