--[[

FillType Helper (Weezls Mod Lib for FS19) - Simplifies the creation of script based mods for FS19

Author:     w33zl (WZL Modding)
Version:    1.0
Modified:   2020-11-04

GitHub:     /w33zl/FS19_WeezlsModLib

Facebook:   "WZL Modding"

Changelog:
v1.0        Initial version

License:    CC BY-NC-SA 4.0
This license allows reusers to distribute, remix, adapt, and build upon the material in any medium or 
format for noncommercial purposes only, and only so long as attribution is given to the creator.
If you remix, adapt, or build upon the material, you must license the modified material under identical terms. 

]]


wml_fillTypeHelper = {
    settings = { useColorfulIcons = false },
    dir = g_currentModDirectory,
    hudDir = "hud"
}




-- function wml_fillTypeHelper:registerFillTypes(callback, customHudDir)
--     self.hudDir = customHudDir or self.hudDir
--     if callback ~= nil and type(callback) == "function" then
--         callback(self)
--     end
-- end

FillTypeManager.loadMapData = Utils.appendedFunction(FillTypeManager.loadMapData, function()
    if wml_fillTypeHelper.registerFillTypes ~= nil and type(wml_fillTypeHelper.registerFillTypes) == "function" then
        wml_fillTypeHelper:registerFillTypes()
    end
end)

local function extendSellStationWithFillType(sellStation, fillTypeName, priceScale)
    -- DebugUtil.printTableRecursively(sellStation, "sellStation:: ", 0, 2)
    local fillTypeIndexToAdd = g_fillTypeManager:getFillTypeIndexByName(fillTypeName)
    local fillTypeToAdd = g_fillTypeManager:getFillTypeByIndex(fillTypeIndexToAdd)
    local price = fillTypeToAdd.pricePerLiter

    local x = {
        fillTypeIndexToAdd = fillTypeIndexToAdd,
        fillTypeToAdd = fillTypeToAdd,
        price = price,
        sellStation = sellStation,
    }

    DebugUtil.printTableRecursively(x, "x:: ", 0, 2)
    
    sellStation:addAcceptedFillType(fillTypeIndexToAdd, price, true, false)
    -- -- local priceMultiplier = sellStation.priceMultipliers[ g_fillTypeManager:getFillTypeIndexByName("EGG")] * 0.99585
    local priceMultiplier = priceScale or 1.0
    -- sellStation.priceMultipliers[ fillTypeIndexToAdd ] = MathUtil.clamp(priceMultiplier, 0.1, 1.0)

    sellStation:initPricingDynamics()
end

SellingStation.load = Utils.appendedFunction(SellingStation.load, function(sellStation, xmlFile, key, customEnvironment, ...)
    if wml_fillTypeHelper.extendSellStation ~= nil and type(wml_fillTypeHelper.extendSellStation) == "function" then
        sellStation.addFillType = extendSellStationWithFillType
        wml_fillTypeHelper:extendSellStation(sellStation, xmlFile, key, customEnvironment, ...)
    end
end)


-- local function loadMaterialHolder(fillTypeName)
--     fillTypeName = tostring(fillTypeName)
--     local filename = Utils.getFilename(string.format( "fillTypes/%s_materialHolder.i3d", fillTypeName ), self.dir)
--     return loadI3DFile(filename, false, true, false)
-- end

-- loadMaterialHolder("sugar")
-- loadMaterialHolder("beetPulp")
-- loadMaterialHolder("feedPellets")

function wml_fillTypeHelper:getHudFileNames(fillTypeName)
    local normalHudFile = string.format( "hud_fill_%s.dds", fillTypeName )
    local smallHudFile = string.format( "hud_fill_%s_sml.dds", fillTypeName )
    return normalHudFile, smallHudFile
end

function wml_fillTypeHelper:getHudDir()
    local hudDirExtra = (self.settings.useColorfulIcons == true and "color/") or ""
    return self.hudDir .. "/" .. hudDirExtra
end

function wml_fillTypeHelper:getFullHudDir()
    return Utils.getFilename(self:getHudDir(), self.dir)
end

---@param fillTypeName string
---@param price float Price (€/$/£) per liter
---@param mass float Mass (kg) per liter
---@param heapAngle float Maximum heap angle (degrees)
function wml_fillTypeHelper:addFillType(fillTypeName, price, mass, heapAngle, hudFilltypeName)
    if fillTypeName == nil or type(fillTypeName) ~= "string" then
        return
    end

    hudFilltypeName = hudFilltypeName or fillTypeName
    local normalHudFile, smallHudFile = self:getHudFileNames(hudFilltypeName)
    local fillPlaneColors = { 1, 1, 1 }
    local hudDir = self:getFullHudDir()

    local fillType = g_fillTypeManager:addFillType(fillTypeName:upper(), g_i18n:getText(fillTypeName), true, price, mass, math.rad(heapAngle), normalHudFile, smallHudFile, hudDir, nil, fillPlaneColors, nil, false)

    if fillType == nil then
        self:printWarning("Failed to add filltype '" .. tostring(fillTypeName).."' to current mission")
    end
end

function wml_fillTypeHelper:addHeightTypeToMission(fillTypeName, heapAngle, allowSmoothing, soundFillTypeName, fillToGroundScale, collisionScale, baseOffset, minOffset, maxOffset)
    local fillTypeIndex = g_fillTypeManager:getFillTypeIndexByName(fillTypeName)

    g_fillTypeManager.fillTypeToSample[fillTypeIndex] = g_fillTypeManager.fillTypeToSample[g_fillTypeManager:getFillTypeIndexByName(soundFillTypeName)]

    -- local function textureFilename(fillTypeName, typeName)
    --     fillTypeName = tostring(fillTypeName)
    --     return Utils.getFilename(string.format( "fillTypes/%s_%s.dds", fillTypeName:lower(), typeName ), self.dir)
    -- end

    local diffuseTextureFilename = Utils.getFilename("fillTypes/" .. fillTypeName .. "_diffuse.dds", self.dir)
    local normalTextureFilename = Utils.getFilename("fillTypes/" .. fillTypeName .. "_normal.dds", self.dir)
    local specularTextureFilename = Utils.getFilename("fillTypes/" .. fillTypeName .. "_specular.dds", self.dir)
    local distanceTextureFilename = Utils.getFilename("fillTypes/" .. fillTypeName .. "_distance_diffuse.dds", self.dir)

    -- Defaults
    fillToGroundScale = fillToGroundScale or 1.0
    collisionScale = collisionScale or 1.0
    baseOffset = baseOffset or 0.0
    minOffset = minOffset or 0.0
    maxOffset = maxOffset or 0.0
    soundFillTypeName = soundFillTypeName or fillTypeName

    local heightType = g_densityMapHeightManager:addDensityMapHeightType(fillTypeName, math.rad(heapAngle), collisionScale, baseOffset, minOffset, maxOffset, fillToGroundScale, allowSmoothing, diffuseTextureFilename, normalTextureFilename, distanceTextureFilename, false)
    if heightType == nil then
        self:printWarning("HeightType '" .. tostring(fillTypeName).."' could not be added to the current mission")
    end
end

function wml_fillTypeHelper:addFillTypeToCategories(fillTypeName, categoryNames)
    local fillTypeIndex = g_fillTypeManager:getFillTypeIndexByName(fillTypeName)

    if fillTypeIndex == nil then
        self:printWarning("Filltype '" .. tostring(fillTypeName).."' was not found")
        return
    end
    
    
    -- self:printDebugVar("FillType " .. fillTypeName, fillTypeIndex)
    for _, category in pairs(categoryNames) do
        self:printDebugVar("Category " .. category, g_fillTypeManager.nameToCategoryIndex[category])
        g_fillTypeManager:addFillTypeToCategory(fillTypeIndex, g_fillTypeManager.nameToCategoryIndex[category])
    end
end


function wml_fillTypeHelper:getFillTypePrice(referenceFillTypeName, priceFactor, fallbackPrice)
    local referenceFilltype = g_fillTypeManager:getFillTypeByName(referenceFillTypeName:upper())

    if referenceFilltype == nil then
        print(string.format( "Filltype '%s' not found, using fallback price", tostring(referenceFillTypeName) ))
        return fallbackPrice
    else
        return referenceFilltype.pricePerLiter * priceFactor
    end

end
