--[[
Interface: 1.7.1.0 b10490

Copyright (C) GtX (Andy), 2020

Author: GtX | Andy
Date: 08.04.2020
Version: 1.0.0.0

Contact:
https://forum.giants-software.com
https://github.com/GtX-Andy

Important:
Free for use in other mods - no permission needed.
No changes are to be made to this script without permission from GtX | Andy

Frei verwendbar - keine erlaubnis nötig
An diesem Skript dürfen ohne Genehmigung von GtX | Andy keine Änderungen vorgenommen werden
]]


local modName = g_currentModName
local modDirectory = g_currentModDirectory

-- Hard coded here so it is guaranteed that the correct l10n is in the mod if another person uses the script in their mod.
local globalTexts = {
    ["statistic_breedHorsesCount"] = {
        en = "Horses bred",
        de = "Pferde gezüchtet",
        fr = "Chevaux élevés",
        es = "Caballos criados"
    },
    ["warning_tooManyBreedingHorses"] = {
        en = "A maximum of 2 horses are required to start breeding!",
        de = "Maximal 2 Pferde sind erforderlich, um mit der Zucht zu beginnen!",
        fr = "Un maximum de 2 chevaux est requis pour commencer l'élevage!",
        es = "¡Se requieren un máximo de 2 caballos para comenzar a reproducirse!"
    },
    ["warning_tooFewBreedingHorses"] = {
        en = "To start breeding, first deliver 2 horses!",
        de = "Um mit der Zucht zu beginnen, liefern Sie zuerst 2 Pferde!",
        fr = "Pour commencer l'élevage, livrez d'abord 2 chevaux!",
        es = "Para comenzar a criar, ¡primero entrega 2 caballos!"
    }
}

local function displayHorse(self, superFunc, horse, husbandry)
    if husbandry.isHorseBreeding and self.showHorseProductivity then
        self.animalDetailHorseBox:setVisible(false)
        self.animalDetailLivestockBox:setVisible(true)

        self:displayLivestock({horse}, husbandry)

        self.animalDetailTypeNameText:setText(horse:getName())
        self.animalDetailTypeCountText:setText("")

        local productivity = husbandry:getGlobalProductionFactor() or 0
        if productivity > 0.995 then
            self.productivityValueText:setText("100%")
        end
    else
        self.animalDetailHorseBox:setVisible(true)
        self.animalDetailLivestockBox:setVisible(false)

        superFunc(self, horse, husbandry)
    end
end

local function updateMenuButtons(self)
    if self.productivityButtonInfo == nil then
        self.showHorseProductivity = false

        self.productivityButtonInfo = {
            inputAction = InputAction.MENU_ACCEPT,
            text = self.l10n:getText("statistic_productivity"),
            callback = function ()
                if self.showHorseProductivity then
                    self.showHorseProductivity = false
                    self.animalDataUpdateTime = -1
                else
                    if self.selectedHusbandry ~= nil then
                        local numHorses = self.selectedHusbandry:getNumOfAnimals()

                        if numHorses == 2 then
                            self.showHorseProductivity = true
                            self.animalDataUpdateTime = -1
                        else
                            local text = self.l10n:getText("warning_tooManyBreedingHorses")

                            if numHorses < 2 then
                                text = self.l10n:getText("warning_tooFewBreedingHorses")
                            end

                            g_gui:showInfoDialog({
                                text = text,
                                dialogType = DialogElement.TYPE_INFO
                            })
                        end
                    end
                end
            end
        }
    end

    if self.selectedHusbandry ~= nil then
        if self.selectedHusbandry.isHorseBreeding and self.selectedHorse ~= nil then
            if self.showHorseProductivity then
                self.productivityButtonInfo.text = self.l10n:getText("ui_statisticViewOverview")
            else
                self.productivityButtonInfo.text = self.l10n:getText("statistic_productivity")
            end

            table.insert(self.menuButtonInfo, self.productivityButtonInfo)

            self:setMenuButtonInfoDirty()
        end
    end
end

local function getStatisticData(self, superFunc)
    local statisticData = superFunc(self)

    -- Only add this if it does not exist already.
    if #statisticData > 1 and self.statisticDataRev["breedHorsesCount"] == nil then
        self:addStatistic("breedHorsesCount", nil, self:getSessionValue("breedHorsesCount"), self:getTotalValue("breedHorsesCount"), "%d")
    end

    return statisticData
end

local function deleteHorseBreeding()
    if g_horseBreedingLoader ~= nil then
        local globalEnv = getfenv(0)

        if globalTexts ~= nil then
            for name, _ in pairs (globalTexts) do
                globalEnv.g_i18n.texts[name] = nil
            end

            globalTexts = nil
        end

        globalEnv.g_horseBreedingLoader = nil
    end
end

local function loadMapFinished()
    if g_horseBreedingLoader == modName then
        if g_seasons == nil and not g_modIsLoaded["FS19_RM_Seasons"] then
            FarmStats.getStatisticData = Utils.overwrittenFunction(FarmStats.getStatisticData, getStatisticData)
            InGameMenuAnimalsFrame.displayHorse = Utils.overwrittenFunction(InGameMenuAnimalsFrame.displayHorse, displayHorse)
            InGameMenuAnimalsFrame.updateMenuButtons = Utils.appendedFunction(InGameMenuAnimalsFrame.updateMenuButtons, updateMenuButtons)

            if globalTexts ~= nil then
                local globalEnv = getfenv(0)

                for name, text in pairs (globalTexts) do
                    globalEnv.g_i18n.texts[name] = Utils.getNoNil(text[g_languageShort], text["en"])
                end
            end
        else
            deleteHorseBreeding()
            print(string.format("  Warning: [HorseBreedingLoader]  Mod '%s' is currently no compatible with Seasons and will not work as intended!", modName))
        end
    end
end

local function initHorseBreeding()
    local placeablePath = modDirectory .. "scripts/HorseBreeding.lua"

    if fileExists(placeablePath) then
        g_placeableTypeManager:addPlaceableType("horseBreeding", "HorseBreeding", placeablePath)

        if g_horseBreedingLoader == nil then
            getfenv(0)["g_horseBreedingLoader"] = modName

            FSBaseMission.delete = Utils.appendedFunction(FSBaseMission.delete, deleteHorseBreeding)
            FSBaseMission.loadMapFinished = Utils.prependedFunction(FSBaseMission.loadMapFinished, loadMapFinished)
        end
    else
        print(string.format("  Error: [HorseBreedingLoader] - [%s]  Required file '%s' could not be found!", modName, placeablePath))
    end
end

initHorseBreeding()
