-- Tell the game the target save file version
-- It will re-save the file with this version
SaveUtil:setSaveFileVersion(5)

-- Process the save file if it's different
local fileData = SaveUtil:readProfiles()

if string.len(fileData) > 0 then
    local profile = cjson.decode(fileData)

    local recordMessage = function(playerProfile, message)
        if playerProfile.messages == nil or playerProfile.messages == cjson.null then
            playerProfile.messages = {}
        end
        table.insert(playerProfile.messages, message)
    end

    local give = function(playerProfile, item, amount)
        if playerProfile.inventory[item] == nil then
            playerProfile.inventory[item] = amount
        else
            playerProfile.inventory[item] = playerProfile.inventory[item] + amount
        end
    end

    if profile.version == 1 or profile.version == nil then
        -- We need to rewrite the save file to add categories to neighborhoods, tutorials and achievements
        local neighbourhoods = require 'Scripts/Data/neighbourhoods.lua'
        local tutorials = require 'Scripts/Data/tutorials.lua'
        local achievements = require 'Scripts/Data/achievements.lua'

        local gatherKeys = function(keySource, keyObjects, keyFields)
            local result = {}
            for i, obj in pairs(keyObjects) do
                for j, field in pairs(keyFields) do
                    local keyValue = obj[field]
                    if keySource[keyValue] ~= nil then
                        result[keyValue] = keySource[keyValue]
                        keySource[keyValue] = nil
                    end
                end
            end

            return result
        end

        profile.playerProfile.neighbourhoods = gatherKeys(profile.playerProfile, neighbourhoods, {'key'})
        profile.playerProfile.tutorials = gatherKeys(profile.playerProfile, tutorials, {'luaPath'})
        profile.playerProfile.achievements = gatherKeys(profile.playerProfile, achievements, {'achievementIdIOS', 'achievementIdGooglePlay'})

        profile.version = 2
    end

    if profile.version == 2 then
        -- Refund all special purchases
        local refund = function(playerProfile, inventory, itemKey, coinCost, toothCost)
            if inventory[itemKey] ~= nil then
                give(playerProfile, "Coin", inventory[itemKey] * coinCost)
                give(playerProfile, "Tooth", inventory[itemKey] * toothCost)
                inventory[itemKey] = nil
            end
        end

        local inventory = profile.playerProfile.inventory

        refund(profile.playerProfile, inventory, 'Typhoon', 500, 0)
        refund(profile.playerProfile, inventory, 'OrbitalPunch', 1000, 0)
        refund(profile.playerProfile, inventory, 'EaglePunch', 1500, 0)
        refund(profile.playerProfile, inventory, 'FistOfTheHeavens', 2000, 0)
        refund(profile.playerProfile, inventory, 'PoultryRain', 2500, 0)

        profile.playerProfile.brick.specialMoveSlot = nil

        recordMessage(profile.playerProfile, "SpecialUpgradeRefund")

        profile.version = 3
    end

    if profile.version == 3 then
        local levels = require 'Scripts/Data/levels.lua'
        
        local bonusTeeth = 0
        
        for i, obj in pairs(levels) do
            local neighborhood = profile.playerProfile.neighbourhoods[levels[i].neighbourhoodKey]
            if neighborhood ~= nil then
                local currentLevel = neighborhood[levels[i].key]
                if currentLevel ~= nil and currentLevel.highScore >=  levels[i].starThreshold3 then
                    bonusTeeth = bonusTeeth + 1
                end
            end
        end
        
        give(profile.playerProfile, "Tooth", bonusTeeth)
        
        recordMessage(profile.playerProfile, "GiveTeethFor3Stars")
        
        profile.version = 4
    end

    if profile.version == 4 then
        local teeth = profile.playerProfile.inventory["Tooth"];
        if teeth ~= nil then
            local bonusCoins = teeth * 20
            profile.playerProfile.inventory["Tooth"] = 0

            give(profile.playerProfile, "Coin", bonusCoins)
        end

        recordMessage(profile.playerProfile, "PremiumTeethConversion")

        profile.version = 5
    end

    fileData = cjson.encode(profile)
    SaveUtil:writeProfiles(fileData)
end