--[[
Script to update existing brands.

Author:  Iceflower S
Version: 22.2022.2.9

History:
22.2022.2.9
    - add brand mapping
22.2022.1.29
    - initial release in FS 22

License (MIT):
Copyright 2022 Iceflower S

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
BrandsXT = {}

BrandsXT.name = "Brands XT"
BrandsXT.id = "brandsXT"
BrandsXT.currentModDirectory = g_currentModDirectory
BrandsXT.debugMode = false

local function getModSettingsFileName()
    return getUserProfileAppPath() .. "modSettings/" .. BrandsXT.id .. ".xml"
end

local function updateBrand(name, title, image, imageShopOverview, imageOffset)
    -- Check if empty or not.
    if name == nil or name == '' then
        print("  Error: (" .. BrandsXT.name .. ") Brand had no name! ('" .. name .. "' | '" .. title .. "' | '" .. image .. "')")
        return
    end
    -- Update only existing brands.
    local brandIdx = g_brandManager.nameToIndex[name]
    if brandIdx == nil then
        print("  Error: (" .. BrandsXT.name .. ") Brand had no index! ('" .. name .. "')")
        return
    end

    print("  Info: (" .. BrandsXT.name .. ") Updating brand '" .. name .. "'")
    -- Update title.
    if title ~= nil then
        -- Get translations.
        if title:sub(1, 6) == "$l10n_" then
            title = g_i18n:getText(title:sub(7))
        end

        g_brandManager.nameToBrand[name].title = title
        g_brandManager.indexToBrand[brandIdx].title = title
    end
    -- Update image and imageShopOverview.
    if image ~= nil then
        local imageFile = ""
        if string.sub(image, 1, 1) == "$" then
            imageFile = string.sub(image, 2)
        else
            imageFile = Utils.getFilename(image, BrandsXT.currentModDirectory)
        end
        if not fileExists(imageFile) then
            print("  Error: (" .. BrandsXT.name .. ") image does not exist! (" .. name .. "): '" .. imageFile .. "'")
            return
        end

        g_brandManager.nameToBrand[name].image = imageFile
        g_brandManager.indexToBrand[brandIdx].image = imageFile
    end
    -- Update imageShopOverview.
    if image ~= nil and imageShopOverview == nil then
        imageShopOverview = image
    end
    if imageShopOverview ~= nil then
        local imageShopOverviewFile = ""
        if string.sub(imageShopOverview, 1, 1) == "$" then
            imageShopOverviewFile = string.sub(imageShopOverview, 2)
        else
            imageShopOverviewFile = Utils.getFilename(imageShopOverview, BrandsXT.currentModDirectory)
        end
        if not fileExists(imageShopOverviewFile) then
            print("  Error: (" .. BrandsXT.name .. ") imageShopOverview does not exist! (" .. name .. "): '" .. imageShopOverviewFile .. "'")
            return
        end

        g_brandManager.nameToBrand[name].imageShopOverview = imageShopOverviewFile
        g_brandManager.indexToBrand[brandIdx].imageShopOverview = imageShopOverviewFile
    end
    -- Update imageOffset.
    if imageOffset ~= nil then
        g_brandManager.nameToBrand[name].imageOffset = imageOffset
        g_brandManager.indexToBrand[brandIdx].imageOffset = imageOffset
    end
end

local function initBrandMapping()
    if fileExists(getModSettingsFileName()) then
        return
    end

    local xmlFile = createXMLFile(BrandsXT.id, getModSettingsFileName(), BrandsXT.id)
    setXMLString(xmlFile, BrandsXT.id .. ".brandsMapping", "")
    saveXMLFile(xmlFile)
    delete(xmlFile)
end

---Load map branding from a file
local function loadBrandMapping(xmlFilename, rootKey, brandMap)
    local xmlFile = loadXMLFile(rootKey, xmlFilename)
    local curBrandIdx = 0
    while true do
        local baseXMLName = string.format(rootKey .. ".brandsMapping.brand(%d)", curBrandIdx)

        if not hasXMLProperty(xmlFile, baseXMLName) then
            break
        end
        local from = getXMLString(xmlFile, baseXMLName .. "#from")
        local to = getXMLString(xmlFile, baseXMLName .. "#to")
        if from == nil or from == "" or to == nil or to == "" then
            print("    Warning (" .. BrandsXT.name .. "): Invalid brand mapping - '" .. from .. "' -> '" .. to .. "'")
        else
            local fromIdx = g_brandManager.nameToIndex[from:upper()]
            local toIdx = g_brandManager.nameToIndex[to:upper()]
            -- Ignore non existing brands
            if fromIdx ~= nil and toIdx ~= nil then
                brandMap[fromIdx] = toIdx
            end
        end

        curBrandIdx = curBrandIdx + 1
    end
    delete(xmlFile)
end

local function updateBrands()
    local brandMap = {}
    initBrandMapping()
    loadBrandMapping(BrandsXT.currentModDirectory .. "modDesc.xml", "modDesc", brandMap)
    loadBrandMapping(getModSettingsFileName(), BrandsXT.id, brandMap)

    -- Change brands based on the mappings
    for fromIdx, toIdx in pairs(brandMap) do
        local fromName = g_brandManager.indexToBrand[fromIdx].name
        local toName = g_brandManager.indexToBrand[toIdx].name
        print("  Info: (" .. BrandsXT.name .. ") Map brand: '" .. fromName .. "' -> '" .. toName .. "'")
        g_brandManager.indexToBrand[fromIdx] = g_brandManager.indexToBrand[toIdx]
        g_brandManager.nameToIndex[fromName] = toIdx
        g_brandManager.nameToBrand[fromName] = g_brandManager.indexToBrand[toIdx]
    end

    -- Update brands
    local modDesc = loadXMLFile("modDesc", BrandsXT.currentModDirectory .. "modDesc.xml")

    local curBrandIdx = 0
    while true do
        local baseXMLName = string.format("modDesc.brands.brand(%d)", curBrandIdx)

        if not hasXMLProperty(modDesc, baseXMLName) then
            break
        end
        local name = getXMLString(modDesc, baseXMLName .. "#name")
        local title = getXMLString(modDesc, baseXMLName .. "#title")
        local image = getXMLString(modDesc, baseXMLName .. "#image")
        local imageShopOverview = getXMLString(modDesc, baseXMLName .. "#imageShopOverview")
        local imageOffset = getXMLFloat(modDesc, baseXMLName .. "#imageOffset")

        updateBrand(name:upper(), title, image, imageShopOverview, imageOffset)

        curBrandIdx = curBrandIdx + 1
    end

    delete(modDesc)
end

Vehicle.init = Utils.prependedFunction(Vehicle.init, updateBrands)
