
local pitStoppedTime = 0
local white=rgbm(.38,0.84,0.83,1)
local classcolor=rgbm(0.0,0.84,0.0,1)
local red=rgbm(0.84,0.0,0.0,1)
local green=rgbm(0,0.84,0.0,1)
local yellow=rgbm(0.84,0.84,0.0,1)
local racePosition = 1
local pitlaneovertime = false
local Timer = 0
local TyreTimer = 0
local FuelTimer = 0
local fueling = false
local actual_fuel = 0
local maxFuel = car.maxFuel
local tyre_change=1
local carini
local tyrechangetime = 0
local carTags
local led_mesh
local class = 0 --- 0 = GT3, 1 = LMP2, 2 = LMH
local classposition={}

function classpositions()
        -- Arrays for each class, no tables
    class0position = {}
    class1position = {}
    class2position = {}

    for i = 0, ac.getSim().carsCount - 1 do
        local tags = ac.getCarTags(i)
        local carclass = 0
        if tags then
            for _, tag in ipairs(tags) do
                if string.find(tag, "GT3") then carclass = 0 break end
                if string.find(tag, "LMP2") then carclass = 1 break end
                if string.find(tag, "LMH") or string.find(tag, "HY") then carclass = 2 break end
            end
        end
        if carclass == 0 then
            class0position[#class0position + 1] = { index = i, pos = ac.getCar(i).racePosition }
        elseif carclass == 1 then
            class1position[#class1position + 1] = { index = i, pos = ac.getCar(i).racePosition }
        elseif carclass == 2 then
            class2position[#class2position + 1] = { index = i, pos = ac.getCar(i).racePosition }
        end
    end

    table.sort(class0position, function(a, b) return a.pos < b.pos end)
    table.sort(class1position, function(a, b) return a.pos < b.pos end)
    table.sort(class2position, function(a, b) return a.pos < b.pos end)



   -- Display the positions for each class
   for i, car in ipairs(class0position) do
       ac.debug('class0position_' .. i, car.pos)
   end
   for i, car in ipairs(class1position) do
       ac.debug('class1position_' .. i, car.pos)
   end
   for i, car in ipairs(class2position) do
       ac.debug('class2position_' .. i, car.pos)
   end
    
end

function position()
    
    classpositions()

    -- Find car's class position
    local classPos = 1
    if class == 0 then
        for i, v in ipairs(class0position) do
            if v.index == car.index then
                classPos = i
                break
            end
        end
    elseif class == 1 then
        for i, v in ipairs(class1position) do
            if v.index == car.index then
                classPos = i
                break
            end
        end
    elseif class == 2 then
        for i, v in ipairs(class2position) do
            if v.index == car.index then
                classPos = i
                break
            end
        end
    end
    racePosition = math.clamp(classPos, 1, 99)
    -- racePosition=math.clamp(car.pos, 1, 99)

    ui.pushDWriteFont('Verdana:../fonts/verdanaz.ttf; Weight=bold; Stretch=Condensed')
    ui.setCursor(vec2(0,0))
    local suffix = 'th'
    local last_digit = racePosition % 10
    local last_two = racePosition % 100

    if last_two ~= 11 and last_two ~= 12 and last_two ~= 13 then
        if last_digit == 1 then
            suffix = 'st'
        elseif last_digit == 2 then
            suffix = 'nd'
        elseif last_digit == 3 then
            suffix = 'rd'
        end
    end

    if racePosition > 9 then
        ui.setCursor(vec2(0,60))
        ui.dwriteTextAligned(racePosition, 160, ui.Alignment.End, ui.Alignment.Start, vec2(240,320), false, classcolor)
        ui.setCursor(vec2(250,92))
        ui.dwriteTextAligned(suffix, 56, ui.Alignment.Start, ui.Alignment.Start, vec2(120,320), false, classcolor)
    else
        ui.dwriteTextAligned(racePosition, 250, ui.Alignment.End, ui.Alignment.Start, vec2(200,320), false, classcolor)
        ui.setCursor(vec2(210,48))
        ui.dwriteTextAligned(suffix, 80, ui.Alignment.Start, ui.Alignment.Start, vec2(120,320), false, classcolor)
    end
end

function pitlanetime()
    ui.pushDWriteFont('Arial:../fonts/arialbd.ttf; Weight=bold; Stretch=Condensed')
    ui.setCursor(vec2(0,50))
    if pitStoppedTime == 99.9 then
        ui.dwriteTextAligned('>1', 180, ui.Alignment.End, ui.Alignment.Start, vec2(205,320), false, white)
        ui.setCursor(vec2(100,48))
        ui.dwriteTextAligned('m', 110, ui.Alignment.End, ui.Alignment.Start, vec2(205,320), false, white)
    else
        local seconds = math.floor(pitStoppedTime)
        local tenths = math.floor(pitStoppedTime * 10) % 10
        ui.dwriteTextAligned(string.format('%02d', seconds), 180, ui.Alignment.End, ui.Alignment.Start, vec2(205,320), false, white)
        ui.setCursor(vec2(40,30))
        ui.dwriteTextAligned('.', 120, ui.Alignment.End, ui.Alignment.Start, vec2(205,320), false, white)
        ui.setCursor(vec2(106,30))
        ui.dwriteTextAligned(tenths, 120, ui.Alignment.End, ui.Alignment.Start, vec2(205,320), false, white)
    end

    ui.drawCircleFilled(vec2(260,216), 60, red, 32)
    ui.setCursor(vec2(214,166))
    ui.dwriteTextAligned('P', 100, ui.Alignment.Center, ui.Alignment.Center, vec2(100,100), false, white)

end

function tyrechange()

    ui.drawRectFilled(vec2(0,0), vec2(320,320), rgbm(0,0,0,1), 0, ui.CornerFlags.None)
    display.image{ image = "TyreChangePlate_GT3.png", pos = vec2(0,40), size = vec2(320,240) }
    ui.pushDWriteFont('Arial:../fonts/arialbd.ttf; Weight=bold; Stretch=Condensed')
    ui.setCursor(vec2(0,50))

    local tyreseconds = math.floor(tyrechangetime - TyreTimer)
    local tyretenths = math.floor((tyrechangetime - TyreTimer) * 10) % 10
    ui.dwriteTextAligned(string.format('%02d', tyreseconds), 180, ui.Alignment.End, ui.Alignment.Start, vec2(205,320), false, white)
    ui.setCursor(vec2(40,30))
    ui.dwriteTextAligned('.', 120, ui.Alignment.End, ui.Alignment.Start, vec2(205,320), false, white)
    ui.setCursor(vec2(106,30))
    ui.dwriteTextAligned(tyretenths, 120, ui.Alignment.End, ui.Alignment.Start, vec2(205,320), false, white)

end

function refueling()
    ui.drawRectFilled(vec2(0,0), vec2(320,320), rgbm(0,0,0,1), 0, ui.CornerFlags.None)
    display.image{ image = "FuelingPlate_GT3.png", pos = vec2(0,40), size = vec2(320,240) }
    local beamwidth, shift = 10, 10
    local fuel = car.fuel
    

    -- Red bar
    if fuel > maxFuel * 0.08 then
        ui.drawRectFilled(vec2(beamwidth+shift,190), vec2(3*beamwidth+shift,270), red, 0, ui.CornerFlags.None)
    end

    -- Yellow bars
    for i = 4, 7, 3 do
        if fuel >= maxFuel * ((i-1)/30 + 0.08) then
            ui.drawRectFilled(vec2(i*beamwidth+shift,190), vec2((i+2)*beamwidth+shift,270), yellow, 0, ui.CornerFlags.None)
        end
    end

    -- Green bars
    for i = 10, 28, 3 do
        if fuel >= maxFuel * ((i-1)/30 + 0.08) then
            ui.drawRectFilled(vec2(i*beamwidth+shift,190), vec2((i+2)*beamwidth+shift,270), green, 0, ui.CornerFlags.None)
        end
    end
end

function carclass()
    carTags = ac.getCarTags(car.index)
    if carTags then
        for _, tag in ipairs(carTags) do
            if string.find(tag, "GT3") then class = 0 break end
            if string.find(tag, "LMP2") then class = 1 break end
            if string.find(tag, "LMH") or string.find(tag, "HY") then class = 2 break end
        end
    end
    if class==0 then classcolor=rgbm(0.0,0.84,0.0,1)
    elseif class==1 then classcolor=rgbm(0.0,0.0,0.84,1)
    elseif class==2 then classcolor=rgbm(0.84,0.0,0.0,1)
    end
end

function init()
    carini = ac.INIConfig.carData(0, 'car.ini')
    tyrechangetime = tonumber(carini.sections.PIT_STOP.TYRE_CHANGE_TIME_SEC[1]) or 0
    led_mesh = ac.findNodes("carRoot:" .. car.index):findMeshes("PositionPanelText_?"):ensureUniqueMaterials()
    carclass()

end

init()

function update(dt)

    ac.debug('class', class)
    -- if car.distanceToCamera > 125 then return end
    

    if car.rpm > 10 then
        if ac.getSunAngle() > 88 then -- emissive property based on sun angle
            ui.drawRectFilled(vec2(0,40), vec2(320,280), rgbm(.05,.05,.05,1), 0, ui.CornerFlags.None)
            led_mesh:setMaterialProperty("ksEmissive",rgb(8,8,8))
        else
            led_mesh:setMaterialProperty("ksEmissive",rgb(6,6,6))
            ui.drawRectFilled(vec2(0,40), vec2(320,280), rgbm(.1,.1,.1,1), 0, ui.CornerFlags.None)
        end
    else
        ui.drawRectFilled(vec2(0,40), vec2(320,280), rgbm(.1,.1,.1,1), 0, ui.CornerFlags.None)
        led_mesh:setMaterialProperty("ksEmissive",rgb(0,0,0))
        display.image{ image = "led_matrix.png", pos = vec2(0,40), size = vec2(320,240) }
        return
    end


    if car.lapCount > 0 and sim.raceSessionType >= 1 and sim.raceSessionType <= 3 then
        if car.isInPitlane then
            pitStoppedTime = math.min(pitStoppedTime + dt, 99.9)
            pitlaneovertime = true
            FuelTimer = FuelTimer + dt
            if FuelTimer > 0.2 then
                if car.fuel > actual_fuel then
                    fueling = true
                    actual_fuel = car.fuel
                else
                    fueling = false
                end
                FuelTimer = 0
            end

            -- tyre_change=-1 : Reifen noch nicht gewechselt
            -- tyre_change=0 : Reifen werden gewechselt
            -- tyre_change=1 : Reifen gewechselt

            if ac.getPatchVersionCode()<3595 then
                if tyre_change==-1 and car.wheels[0].tyreGrain == 0 then
                    tyre_change=0
                    TyreTimer = tyrechangetime
                end

                if tyre_change==0 then
                    TyreTimer = TyreTimer - dt
                    if TyreTimer < 0 then
                        tyre_change=1
                    end
                end
            else
                if car.isChangingTyres then
                    tyre_change=0
                    TyreTimer = TyreTimer - dt
                    if TyreTimer < 0 then
                        tyre_change=1
                    end
                else
                    TyreTimer = tyrechangetime
                end
            end



        else
            
            if pitlaneovertime then
                Timer = Timer > 500 and 0 or Timer + dt
                if Timer > 5 then
                    pitlaneovertime = false
                    Timer = 0
                end
            end
            actual_fuel=car.fuel
            tyre_change=-1

        end

        if pitlaneovertime then
            pitlanetime()
            if fueling then
                refueling()
            end
            if tyre_change==0 and sim.isReplayActive==false then
                tyrechange()
            end
        else
            position()
            pitStoppedTime=0
        end

    else
        if class==0 then
            display.image{ image = "PositionPlate_GT3.png", pos = vec2(0,40), size = vec2(320,240) }
        elseif class==1 then
            display.image{ image = "PositionPlate_LMP2.png", pos = vec2(0,40), size = vec2(320,240) }
        elseif class==2 then
            display.image{ image = "PositionPlate_LMH.png", pos = vec2(0,40), size = vec2(320,240) } 
        end
    end

    display.image{ image = "led_matrix.png", pos = vec2(0,40), size = vec2(320,240) }


    ac.debug('tyre_change', tyre_change)
    ac.debug('tyreGrain', car.wheels[0].tyreGrain)
    ac.debug('carini', carini)
    ac.debug('tyrechangetime', tyrechangetime)
    ac.debug('tyrechangetime', ac.getCar(0))
    ac.debug('car.index', car.index)
    ac.debug('ac.getCarTags', ac.getCarTags(car.index))
    ac.debug('FuelTimer', FuelTimer)
    ac.debug('TyreTimer', TyreTimer)
    ac.debug('sun', ac.getSunAngle())

    -- ac.debug('isRepairing', car.isRepairing )
    -- ac.debug('isRefueling', car.isRefueling )
    -- ac.debug('isChangingTyres', car.isChangingTyres )
    -- ac.debug('isRequestingPitStop', car.isRequestingPitStop )
    ac.debug('carsCount', ac.getSim().carsCount)
    ac.debug('getPatchVersion', ac.getPatchVersionCode())



end