TopScores = {}

function TopScores:new()
    local ts = copy_table(self)
    ts:load()
    return ts
end


function TopScores:load()
    self.chart = {}
    
    if file_exists("profiles/top_scores.sav") then
        local data = file_load_lua_table("profiles/top_scores.sav")
        local count = 0

        for k, v in pairs(data) do
            self.chart[k] = v
            count = count + 1
        end

        log("Loaded top scores for "..count.." adventures")
    end
end


function TopScores:save()
    local data = ""
    local count = 0
    
    for k, v in pairs(self.chart) do
        data = data.."[\""..k.."\"] = {\n"
        for i, score in ipairs(v) do
            -- trim records, but keep scores that need to be sent online
            if i <= 10 or (score.online and not score.sent) then
                data = data.."    {\n"
                data = data.."        name = \""..score.name.."\",\n"
                data = data.."        player_guid = \""..score.player_guid.."\",\n"
                data = data.."        score = "..score.score..",\n"
                data = data.."        online = "..tostring(score.online)..",\n"
                data = data.."    },\n"
            end
        end
        data = data.."},\n\n"

        count = count + 1
    end

    file_save("profiles/top_scores.sav", data, compress_sensitive_data)
    log("Saved top scores for "..count.." adventures")
end



function TopScores:add_score(adventure_guid, player_guid, player_name, score, send_online)
    log("New score: "..score.." by "..player_name.." (online? "..tostring(send_online)..")")
    
    self.chart[adventure_guid] = self.chart[adventure_guid] or {}
    local score = {
        name = player_name,
        player_guid = player_guid,
        score = score,
        online = send_online,
    }
    table.insert(self.chart[adventure_guid], score)

    table.sort(self.chart[adventure_guid], function(a,b) return a.score > b.score end)
    self:save()
    
    if send_online and send_score then
        local job_data = {
        	["product_code"] = kiss.project_code,
        	["score[player_guid]"] = score.player_guid,
        	["score[player_name]"] = score.name,
        	["score[adventure_guid]"] = adventure_guid,
        	["score[score]"] = score.score,
        	["score[build_number]"] = kiss.app_build,
        }
        fw:net_queue_post(job_data, "/score/create")
    end
end


function TopScores:get_scores_for_adventure(adventure_guid)
    return self.chart[adventure_guid]
end
