#include "../config/events.lua"
#include "helpers/mathfr.lua"

money = {}

local REG_NAME_VAR = "savegame.mod.money"
function money:SetMoney(amount)
    SetInt(REG_NAME_VAR, amount > 0 and amount or 0)
end

function money:AddMoney(amount)
    if amount < 0 then
        return
    end
    local total = GetInt(REG_NAME_VAR)
    total = amount + total 
    SetInt(REG_NAME_VAR, total)
end

function money:PayMoney(amount)
    local total = GetInt(REG_NAME_VAR)
    if total >= amount then
        total = total - amount
        SetInt(REG_NAME_VAR, total)
        return true
    else
        return false
    end
end

function money:GetMoney()
    local total = GetInt(REG_NAME_VAR)
    return total
end

function money:DigitsNum()
    local total = GetInt(REG_NAME_VAR)
    return math:NumOfDigits(total)
end

-- unsafe
function money:GetStringMoney(total)
    local temp = total
    local money_str = ""
    while math:NumOfDigits(temp) > 3 do
        local temp_last = temp % 1000
        temp = math.floor(temp / 1000)

        if temp_last < 10 then
            temp_last = "00"..temp_last
        elseif temp_last < 100 then
            temp_last = "0"..temp_last
        end

        money_str = ","..temp_last..money_str
    end
    money_str = temp..money_str
    return money_str
end
