-- =========================================================
-- Speed Camera BR — Propriedade dos Radares (SpeedCameraOwner)
-- =========================================================
-- Igual à Cooperativa: a PRIMEIRA fazenda que colocar um radar vira
-- a dona. Só ela pode colocar mais radares. As multas vão pra ela.
--
-- Persiste no savegame e sincroniza no MP.
-- =========================================================

SpeedCameraOwner = {}

-- Fazenda dona dos radares (0 = ninguém ainda)
SpeedCameraOwner.ownerFarmId = 0

function SpeedCameraOwner.hasOwner()
    return SpeedCameraOwner.ownerFarmId ~= nil and SpeedCameraOwner.ownerFarmId > 0
end

function SpeedCameraOwner.isOwner(farmId)
    if farmId == nil then return false end
    return tonumber(farmId) == tonumber(SpeedCameraOwner.ownerFarmId)
end

-- Define o dono (primeira colocação). Só funciona se ainda não há dono.
function SpeedCameraOwner.claimOwnership(farmId)
    if SpeedCameraOwner.hasOwner() then
        return false  -- já tem dono
    end
    if farmId == nil or farmId <= 0 then
        return false
    end
    SpeedCameraOwner.ownerFarmId = farmId
    SpeedCameraOwner.save()
    print(string.format("[SpeedCameraBR] Fazenda %d agora é DONA dos radares", farmId))
    return true
end

function SpeedCameraOwner.setOwner(farmId)
    SpeedCameraOwner.ownerFarmId = tonumber(farmId) or 0
end

-- Nome da fazenda dona (pra exibição)
function SpeedCameraOwner.getOwnerName()
    if not SpeedCameraOwner.hasOwner() then
        return "?"
    end
    if g_farmManager then
        local farm = g_farmManager:getFarmById(SpeedCameraOwner.ownerFarmId)
        if farm and farm.name and farm.name ~= "" then
            return farm.name
        end
    end
    return string.format("Fazenda %d", SpeedCameraOwner.ownerFarmId)
end

-- ─── Persistência ────────────────────────────────────────
function SpeedCameraOwner.getPath()
    if g_currentMission == nil or g_currentMission.missionInfo == nil then return nil end
    local dir = g_currentMission.missionInfo.savegameDirectory
    if dir == nil then return nil end
    return dir .. "/speedCameraOwner.xml"
end

function SpeedCameraOwner.load()
    local path = SpeedCameraOwner.getPath()
    if path == nil or not fileExists(path) then return end
    local xml = loadXMLFile("SCOwner", path)
    if xml == nil or xml == 0 then return end
    local o = getXMLInt(xml, "speedCameraOwner.ownerFarmId")
    if o ~= nil then SpeedCameraOwner.ownerFarmId = o end
    delete(xml)
    print(string.format("[SpeedCameraBR] Dono carregado: farmId=%d",
        SpeedCameraOwner.ownerFarmId))
end

function SpeedCameraOwner.save()
    local path = SpeedCameraOwner.getPath()
    if path == nil then return end
    local xml = createXMLFile("SCOwner", path, "speedCameraOwner")
    setXMLInt(xml, "speedCameraOwner.ownerFarmId", SpeedCameraOwner.ownerFarmId)
    saveXMLFile(xml)
    delete(xml)
end
