cfg = require ('industryConfig')

industryDesc = {
["DUMMY"] = _(DUMMY_desc),                          	--(Devilhunter) Заглушка, чтобы заводы не из мода не приводили к вылету
["Chemical plant"] = _(Chemical_desc),					-- Химзавод
["Coal mine"] = _(Coal_desc),							-- Угольная шахта
["Construction materials plant"] = _(Construction_desc),-- Завод Строй Материалов
["Farm"] = _(Farm_desc),								-- Ферма
["Food processing plant"] = _(Food_desc),				-- Пищевая фабрика
["Forest"] = _(Forest_desc),							-- Лесозаготовка
["Goods factory"] = _(Goods_desc),						-- Производственное предприятие
["Iron ore mine"] = _(Iron_desc),						-- Железный рудник
["Machine factory"] = _(Machine_desc),					-- Машиностроительныц завод
["Oil refinery"] = _(Oil_refinery_desc),				-- Нефтеперерабатывающий завод
["Oil well"] = _(Oil_well_desc),						-- Нефтянная скважина
["Quarry"] = _(Quarry_desc),							-- Карьер -
["Saw mill"] = _(Saw_mill_desc),						-- Лесопилка
["Steel mill"] = _(Steel_mill_desc),					-- Сталелитейный Завод
-- Индустрия
["Cotton plantation"] = _(Cotton_desc),					-- Хлопковая ферма
["Dairy farm"] = _(Dairy_desc),							-- Молочная ферма
["Power plant"] = _(Power_desc),						-- Электростанция
["Fertilizers factory"] = _(Fertilizer_desc),			-- Завод удобрений
["Grain silo"] = _(Grain_desc),							-- Зернохранилище
["Landfill"] = _(Landfill_desc),						-- Свалка
["Textile factory"] = _(Textile_desc),					-- Текстильная фабрика
["Cement factory"] = _(Cement_desc),					-- Цементный завод
-- Коммерция
["Raceway"] = _(Raceway_desc),							-- Гоночная трасса
-- ["Имя завода"] = переменная описания,]]
}
--Блок для локализации
--RU
industryDesc['Хлопковая ферма'] = industryDesc["Cotton plantation"]
industryDesc['Молочная ферма'] = industryDesc["Dairy farm"]
industryDesc['Электростанция'] = industryDesc["Power plant"]
industryDesc['Завод удобрений'] = industryDesc["Fertilizers factory"]
industryDesc['Зернохранилище'] = industryDesc["Grain silo"]
industryDesc['Свалка'] = industryDesc["Landfill"]
industryDesc['Текстильная фабрика'] = industryDesc["Textile factory"]
industryDesc['Гоночная трасса'] = industryDesc["Raceway"]
industryDesc['Цементный завод'] = industryDesc["Cement factory"]
--DE
industryDesc['Baumwollplantage'] = industryDesc["Cotton plantation"]
industryDesc['Milchfabrik'] = industryDesc["Dairy farm"]
industryDesc['Kraftwer'] = industryDesc["Power plant"]
industryDesc['Düngemittelfabrik'] = industryDesc["Fertilizers factory"]
industryDesc['Getreidespeicher'] = industryDesc["Grain silo"]
industryDesc['Mülldeponi'] = industryDesc["Landfill"]
industryDesc['Textilfabrik'] = industryDesc["Textile factory"]
industryDesc['Speedwayrennen'] = industryDesc["Raceway"]
industryDesc['Zementwerk'] = industryDesc["Cement factory"]
--PL
industryDesc['Farma bawełny'] = industryDesc["Cotton plantation"]
industryDesc['Farma mleczna'] = industryDesc["Dairy farm"]
industryDesc['Zakład elektryczny'] = industryDesc["Power plant"]
industryDesc['Zakład rolniczy'] = industryDesc["Fertilizers factory"]
industryDesc['Spichlerz'] = industryDesc["Grain silo"]
industryDesc['Wysypisko'] = industryDesc["Landfill"]
industryDesc['Fabryka odzieży'] = industryDesc["Textile factory"]
industryDesc['żużel'] = industryDesc["Raceway"]
industryDesc['Betoniarnia'] = industryDesc["Cement factory"]


local function constructionCallback(fileName, data)
	if data.type == "INDUSTRY" then
		if industryDesc[data.description.name] then
			data.description.description = industryDesc[data.description.name]
		else
			data.description.description = industryDesc["DUMMY"]
		end
	end
	local fn = data.updateFn
	data.updateFn = function(params)
		local result = fn(params)
		if data.type == "INDUSTRY" then
			result.cost = cfg.giveCost(data.description.name) * (params.productionLevel + 1)
			result.maintenanceCost = cfg.giveRunning(data.description.name) * (params.productionLevel + 1)
		end	
		return result
	end
	return data
end

--Добавление возможности перевозки грузов из мода для всех грузовых транспортных средств
--Описание ванильных грузовых транспортных средств
local stdOpen = {"COAL", "IRON_ORE", "STONE", "GRAIN", "SLAG"}
local stdBox = {"LIVESTOCK", "PLASTIC", "MACHINES", "TOOLS", "FOOD", "GOODS"}
local stdTank = {"CRUDE", "OIL", "FUEL"}
local stdFlat = {"LOGS", "STEEL", "PLANKS", "CONSTRUCTION_MATERIALS"}
local stdTruck = {"LOGS", "LIVESTOCK", "COAL", "IRON_ORE", "STONE", "GRAIN", "CRUDE", "STEEL", "PLANKS", "PLASTIC", "SLAG", "OIL", "CONSTRUCTION_MATERIALS", "MACHINES", "FUEL",
				  "TOOLS", "FOOD", "GOODS"}
local stdHopper = {"GRAIN"}
local stdRef = {"FOOD"}
local stdTransport = {stdOpen, stdBox, stdTank, stdFlat, stdTruck, stdHopper, stdRef}
--Описание грузов, которые необходимо добавить грузовым транспортным средствам
local modOpen = {"WASTE", "LIMESTONE", "MINERALS"}
local modBox = {"COTTON", "CLOTHES"}
local modTank = {"MILK", "CHEMICAL", "FERTILIZERS"}
local modFlat = {}
local modTruck = {"WASTE", "MILK", "COTTON", "CLOTHES", "FERTILIZERS", "CHEMICAL", "MINERALS", "LIMESTONE", "CEMENT"}
local modHopper = {"CEMENT"}
local modRef = {}
local modTransport = {modOpen, modBox, modTank, modFlat, modTruck, modHopper, modRef}
local vehiclesDoNotModify = {
							 _("American horse cart"),
							 _("Ford Model 77"),
							 _("Gondola"), -- Американский насыпной вагон
							 _("Open wagon"), -- Европейский насыпной вагон
							 _("Horse cart"),
							 _("Mack AC"),
							 _("Steam Lorry"),
							 _("Studebaker US6 U3"),
							 _("Studebaker US6 U5"),
							 _("Studebaker US6 U10"),
							}
local function inList(list, value)
	for i = 1, #list do
		if list[i] == value then return true end
	end
	return false
end

function round(num, idp)
  local mult = 10^(idp or 0)
  return math.floor(num * mult + 0.5) / mult
end

function canCarryAll(capacities, list)
	counter = 0
	averageCapacity = 0
	for i = 1, #capacities do
		if inList(list, capacities[i].type) then
			counter = counter + 1
			averageCapacity = averageCapacity + capacities[i].capacity
		end
	end
	if counter == #list and counter == #capacities then return {true, round(averageCapacity / counter)}
	else return {false, 0} end
end

local function modelCallback(fileName, data)
	if data.metadata.transportVehicle and data.metadata.description and not inList(vehiclesDoNotModify, data.metadata.description.name) then
		if data.metadata.transportVehicle.capacities then
			for i = 1, #stdTransport do
				transp = canCarryAll(data.metadata.transportVehicle.capacities, stdTransport[i])
				if transp[1] then
					for j = 1, #modTransport[i] do
						data.metadata.transportVehicle.capacities[#data.metadata.transportVehicle.capacities + 1] = {type = modTransport[i][j], capacity = transp[2]}
					end
					break
				end
			end
		end
	end
	return data
end

function data()
	return {
		info = {
			minorVersion = 0,
			severityAdd = "NONE",
			severityRemove = "CRITICAL",
			name = _(info_name),
			description = _(info_desc),
			tags = {"Industry","Script Mod","Wagon","Misc"},
			authors = {
				{
					name = 'Vitaro', role = 'Creator',
					name = 'Mr.Kot"13"', role = 'Test',
					name = 'kiemas', role = 'Translation into Poland',
					name = 'Devilhunter', role = 'Script',
					name = 'pav', role = '3d model',
					name = 'tirkaz', role = 'Translation into English',
					name = 'Shadowmio', role = 'Translation into German',
					name = 'Oldkestas', role = 'Textures',
					name = 'Ural102', role = '3d model',
					name = 'Old', role = '3d model',
					name = 'Alex', role = '3d model',
				}
			},
			visible = true,
		},
		
		options = { },

		runFn = function (settings)
			addModifier("loadModel", modelCallback)
			addModifier("loadConstruction", constructionCallback)
			

			game.config.industryButton = true
			
			game.config.cargotypes = {
			-- Base (Базовые)
			{ id = "PASSENGERS", name = _("Passengers") },		-- пассажиры
			{ id = "LOGS", name = _("Logs") },					-- бревна
			{ id = "LIVESTOCK", name = _("Livestock") },		-- скот
			{ id = "COAL", name = _("Coal") },					-- уголь
			{ id = "IRON_ORE", name = _("Iron ore") },			-- железо
			{ id = "STONE", name = _("Stone") },				-- камень
			{ id = "GRAIN", name = _("Grain") },				-- зерно (Нужен спец вагон)
			{ id = "CRUDE", name = _("Crude oil") },			-- сырая нефть
			{ id = "STEEL", name = _("Steel") },				-- сталь	
			{ id = "PLANKS", name = _("Planks") },				-- доски
			{ id = "PLASTIC", name = _("Plastic") },			-- пластик
			{ id = "SLAG", name = _("Slag") },					-- шлак
			{ id = "OIL", name = _("Oil") },					-- нефть
			{ id = "CONSTRUCTION_MATERIALS", name = _("Construction material") },	-- строительные материалы
			{ id = "MACHINES", name = _("Machines") },			-- Техника
			{ id = "FUEL", name = _("Fuel") },					-- Топливо
			{ id = "TOOLS", name = _("Tools") },				-- Инструменты
			{ id = "FOOD", name = _("Food") },					-- Пища
			{ id = "GOODS", name = _("Goods") },				-- Товары
			-- New (Новые)
			{ id = "WASTE", name = _("Waste") },				-- Отходы
			-- { id = "ALUMINUM", name = _("Aluminum") },		-- Алюминий
			-- { id = "BAUXITE", name = _("Bauxite") },			-- Бокситы
			{ id = "MILK", name = _("Milk") },					-- Молоко
			{ id = "COTTON", name = _("Cotton") },				-- Хлопок
			{ id = "CLOTHES", name = _("Clothes") },			-- Одежда
			{ id = "FERTILIZERS", name = _("Fertilizers") },	-- Удобрения
			{ id = "CHEMICAL", name = _("Chemicals") },			-- Химия
			-- { id = "PAPER", name = _("Paper") },				-- Бумага 
			-- { id = "FILINGS", name = _("Filings") },			-- Опилки
			 { id = "CEMENT", name = _("Cement") },				-- Цемент (Нужен спец вагон)
			 { id = "LIMESTONE", name = _("Limestone") },		-- Известняк
			 { id = "MINERALS", name = _("Minerals") },			-- Минералы
			-- { id = "RUBBER", name = _("Rubber") },			-- Резина
			-- { id = "CARS", name = _("Cars") },				-- Автомобили (Нужен спец вагон)
			-- { id = "COM_AUTO", name = _("Special Vehicles") },			-- Спец техника (Нужен спец вагон)
			{ id = "URAN", name = _("Uranium") },					-- Уран
			-- { id = "EMPTY", name = _("Empty") },				-- Заглушка
			}
		end
	
	}

end