--[[
Interface: 1.6.0.0 b9173

Copyright (C) GtX (Andy), 2018

Author: GtX | Andy
Date: 09.12.2018
Version: 1.0.0.0

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

History:
V 1.1.0.0 @ 01.10.2020 - Update to support 'milkContractorPercent', fixed bug with 'multiTextOption' so controllers work better, added support for milkAddon settings.

Important:
Not to be added to any mods / maps or modified from its current release form.
No changes are to be made to this script without permission from GtX | Andy

Darf nicht zu Mods / Maps hinzugefügt oder von der aktuellen Release-Form geändert werden.
An diesem Skript dürfen ohne Genehmigung von GtX | Andy keine Änderungen vorgenommen werden
]]


MilkSaleDialog = {}

MilkSaleDialog.MILK_TRUCK_VOLUME = 32000 -- mks32 tanker size.
MilkSaleDialog.MILK_TRUCK_TRIP_FEE = 500 -- Minimum cost for each 32000L trip.
MilkSaleDialog.MILK_TRUCK_BACKUP_PERCENT = 0.05 -- Backup percent charged for volume sold.

MilkSaleDialog.CONTRACTOR_TRUCKS = {
    "data/vehicles/lizard/truckS/store_truckS.dds",
    "data/vehicles/man/tgs18500/store_tgs18500.dds",
    "data/vehicles/lizard/truckL/store_truckL.dds",
    "data/vehicles/tatra/tatraPhoenix/store_tatraPhoenix.dds",
    "data/vehicles/lizard/truckM/store_truckM.dds"
}

MilkSaleDialog.CONTROLS = {
    MESSAGE_BACKGROUND = "messageBackground",
    DESCRIPTION_TEXT = "descriptionText",
    AMOUNT_TEXT = "amountText",
    CAPACITY_TEXT = "capacityText",
    MARKET_VALUE_TEXT = "marketValueText",
    SALE_PRICE_VALUE = "salePriceValue",
    FEE_VALUE = "feeValue",
    TOTAL_VALUE = "totalValue",
    LITRES_TO_SELL_ELEMENT = "litresToSellElement",
    INFO_BOX_TEXT = "infoBoxText",
    TRUCK_IMAGE_ELEMENT = "truckImageElement",
    TRAILER_IMAGE_ELEMENT = "trailerImageElement"
}

local MilkSaleDialog_mt = Class(MilkSaleDialog, YesNoDialog)

function MilkSaleDialog:new(target, texts, customMt)
    local self = YesNoDialog:new(target, customMt or MilkSaleDialog_mt)

    self:registerControls(MilkSaleDialog.CONTROLS)

    self.texts = texts
    self.target = target
    self.litresToSell = 0
    self.areButtonsDisabled = false
    self.sellPointUpdateTimer = 600

    self.lastMilkContractorPercent = 5
    self.milkContractorPercentChanged = false

    return self
end

function MilkSaleDialog:setData(fillLevel, capacity)
    self.lastLitresToSell = -1
    self.lastCurrentMarketValue = -1

    self.availableSellPoints = {}

    for _, unloadingStation in pairs (g_currentMission.storageSystem.unloadingStations) do
        if unloadingStation.isSellingPoint and unloadingStation.fillTypePrices[FillType.MILK] ~= nil and unloadingStation.fillTypePrices[FillType.MILK] > 0 then
            table.insert(self.availableSellPoints, unloadingStation)
        end
    end

    self.bestSellPoint, self.currentMarketValue = self:getSellPointData()

    self.litresToSellTable = {0}
    local litresToSellMapping = {g_i18n:formatFluid(0, 0)}

    if fillLevel >= 1 then
        if fillLevel < 1000 then
            self.litresToSellTable[2] = fillLevel
            litresToSellMapping[2] = g_i18n:formatFluid(fillLevel, 0)
        else
            local mapping = 0

            while mapping < fillLevel do
                mapping = mapping + math.min(1000, (fillLevel - mapping))

                table.insert(self.litresToSellTable, mapping)
                table.insert(litresToSellMapping, g_i18n:formatFluid(mapping, 0))
            end
        end
    end

    self.litresToSellElement:setTexts(litresToSellMapping)
    self.litresToSellElement:setState(1, true)

    self.amountText:setText(self.texts.amount)
    self.descriptionText:setText(self.texts.description)
    self.capacityText:setText(string.format(self.texts.milkCapacity, g_i18n:formatFluid(capacity, 0)))
    self.marketValueText:setText(string.format(self.texts.marketValue, g_i18n:formatMoney((self.currentMarketValue * 1000), 0, true, false)))

    if self.bestSellPoint ~= nil then
        local truckId = math.random(1, 5)

        self.truckImageElement:setImageFilename(MilkSaleDialog.CONTRACTOR_TRUCKS[truckId])
        self.trailerImageElement:setImageFilename("data/vehicles/lizard/mks32/store_mks32.dds")
        self.truckImageElement:setVisible(true)
        self.trailerImageElement:setVisible(true)

        self:setMultiTextElementDisabled(self.litresToSellElement, false, true)
    else
        self.truckImageElement:setVisible(false)
        self.trailerImageElement:setVisible(false)
        self.infoBoxText:setText(self.texts.noMilkSellPointWarning)
        self.infoBoxText:setTextColor(0.8069, 0.0097, 0.0097, 1)

        self:setMultiTextElementDisabled(self.litresToSellElement, true, false)
    end

end

function MilkSaleDialog:getSellPointData()
    local bestSellPoint
    local highestValue = 0
    local numSellPoints = #self.availableSellPoints

    if numSellPoints > 0 then
        for i = 1, numSellPoints do
            local sellPoint = self.availableSellPoints[i]
            local price = sellPoint:getEffectiveFillTypePrice(FillType.MILK)

            if price ~= nil and price > highestValue then
                highestValue = price
                bestSellPoint = sellPoint
            end
        end

        if bestSellPoint ~= nil then
            return bestSellPoint, highestValue
        end
    end

    return nil, 0.0
end

function MilkSaleDialog:getContractorFee(numTrips, salePrice)
    if salePrice > 0 then
        numTrips = numTrips or 1

        local contractorPercent = MilkSaleDialog.MILK_TRUCK_BACKUP_PERCENT

        if self.lastMilkContractorPercent ~= nil then
            contractorPercent = MathUtil.clamp(self.lastMilkContractorPercent, 0, 100) * 0.01
        end

        if contractorPercent > 0 then
            return math.floor((salePrice * contractorPercent) + (MilkSaleDialog.MILK_TRUCK_TRIP_FEE * numTrips))
        end

        return MilkSaleDialog.MILK_TRUCK_TRIP_FEE * numTrips
    end

    return 0
end

function MilkSaleDialog:update(dt)
    MilkSaleDialog:superClass().update(self, dt)

    self.sellPointUpdateTimer = self.sellPointUpdateTimer - dt

    if g_animalPenExtensionManager ~= nil then
        if self.lastMilkContractorPercent ~= g_animalPenExtensionManager.milkContractorPercent then
            self.lastMilkContractorPercent = g_animalPenExtensionManager.milkContractorPercent

            self.milkContractorPercentChanged = true
            self.sellPointUpdateTimer = -1
        end
    end

    if self.sellPointUpdateTimer < 0 then
        self.bestSellPoint, self.currentMarketValue = self:getSellPointData()
        self:updatePrices(true)

        self.sellPointUpdateTimer = 600
    end
end

function MilkSaleDialog:onClickSellAmount(id)
    self.litresToSell = self.litresToSellTable[id]
    self:updatePrices(false)
end

function MilkSaleDialog:updatePrices(isUpdate)
    if (self.litresToSell ~= self.lastLitresToSell) or (self.currentMarketValue ~= self.lastCurrentMarketValue) or self.milkContractorPercentChanged then
        self.lastLitresToSell = self.litresToSell
        self.lastCurrentMarketValue = self.currentMarketValue
        self.milkContractorPercentChanged = false

        if isUpdate then
            self.marketValueText:setText(string.format(self.texts.marketValue, g_i18n:formatMoney((self.currentMarketValue * 1000), 0, true, false)))
        end

        if self.litresToSell >= 1 then
            self:setButtonDisabled(false)

            local numTrips = math.ceil((self.litresToSell / MilkSaleDialog.MILK_TRUCK_VOLUME))
            local salePrice = self.litresToSell * self.currentMarketValue

            self.contractorFee = self:getContractorFee(numTrips, salePrice)

            self.salePriceValue:setText(g_i18n:formatMoney(salePrice, 0, true, false))
            self.feeValue:setText(g_i18n:formatMoney(-self.contractorFee, 0, true, false))
            self.totalValue:setText(g_i18n:formatMoney((salePrice - self.contractorFee), 0, true, false))
        else
            local value = g_i18n:formatMoney(0, 0, true, false)

            self:setButtonDisabled(true)

            self.salePriceValue:setText(value)
            self.feeValue:setText(value)
            self.totalValue:setText(value)

            self.contractorFee = 0
        end
    end
end

function MilkSaleDialog:sendCallback(litresToSell, contractorFee, bestSellPoint)
    if self.inputDelay < self.time then
        self:close()

        if self.callbackFunc ~= nil and self.target ~= nil then
            self.callbackFunc(self.target, litresToSell, contractorFee, bestSellPoint)
        end
    end
end

function MilkSaleDialog:onClickOk()
    if self.areButtonsDisabled then
        return true
    end

    self:sendCallback(self.litresToSell, self.contractorFee, self.bestSellPoint)

    return false
end

function MilkSaleDialog:onClickBack()
    self:sendCallback(0)

    return false
end

function MilkSaleDialog:setMultiTextElementDisabled(element, disabled, updateOverlayState)
    -- Fix for a bug that does not reset the childElements correctly after they are disabled.
    if element ~= nil then
        element:setDisabled(disabled, updateOverlayState)

        if updateOverlayState then
            for _, childElement in pairs(element.elements) do
                childElement:setDisabled(disabled)
                childElement:setOverlayState(element.overlayState)
            end
        end
    end
end

function MilkSaleDialog:setButtonDisabled(disabled)
    self.areButtonsDisabled = disabled
    self.yesButton:setDisabled(disabled)
end
