RealisticDieselPrice = {
    currentState = 1,
    saveFile = "aaRealisticDieselPrice.xml",
    priceOptions = {
        { price = 1.50 },
        { price = 6.40 },
        { price = 1.88 },
        { price = 1.59 }
    }
}

function RealisticDieselPrice:getSavePath()
    local missionInfo = g_currentMission ~= nil and g_currentMission.missionInfo or nil
    local directory = missionInfo ~= nil and missionInfo.savegameDirectory or nil
    return directory ~= nil and (directory .. "/" .. self.saveFile) or nil
end

function RealisticDieselPrice:applyCurrentPrice()
    local option = self.priceOptions[self.currentState]
    local diesel = g_fillTypeManager ~= nil and g_fillTypeManager:getFillTypeByName("DIESEL") or nil
    if option ~= nil and diesel ~= nil then diesel.pricePerLiter = option.price end
end

function RealisticDieselPrice:saveSettings()
    if g_server == nil then return end
    local path = self:getSavePath()
    if path == nil then return end
    local xml = XMLFile.create("aaRealisticDieselPrice", path, "settings")
    if xml == nil then return end
    xml:setInt("settings#state", self.currentState)
    xml:save()
    xml:delete()
end

function RealisticDieselPrice:loadSettings()
    local path = self:getSavePath()
    if path ~= nil and fileExists(path) then
        local xml = XMLFile.loadIfExists("aaRealisticDieselPrice", path)
        if xml ~= nil then
            local state = xml:getInt("settings#state", self.currentState)
            if self.priceOptions[state] ~= nil then self.currentState = state end
            xml:delete()
        end
    end
    self:applyCurrentPrice()
end

function RealisticDieselPrice:setState(state, save)
    state = math.floor(tonumber(state) or 1)
    if self.priceOptions[state] == nil then state = 1 end
    self.currentState = state
    self:applyCurrentPrice()
    if save then self:saveSettings() end
end

Mission00.loadMission00Finished = Utils.appendedFunction(Mission00.loadMission00Finished, function()
    RealisticDieselPrice:loadSettings()
end)

FSCareerMissionInfo.saveToXMLFile = Utils.appendedFunction(FSCareerMissionInfo.saveToXMLFile, function()
    RealisticDieselPrice:saveSettings()
end)

if FSBaseMission.sendInitialClientState ~= nil then
    FSBaseMission.sendInitialClientState = Utils.appendedFunction(FSBaseMission.sendInitialClientState, function(self, connection)
        if g_server ~= nil then connection:sendEvent(RealisticDieselPriceEvent.new(RealisticDieselPrice.currentState)) end
    end)
end
