-- Получаем ID машины
local carID = ac.getCarID(0)

-- Проверяем ID машины
if carID ~= "lew1x_bmw_m2_g87_at_s2" then
    -- Выдаем ошибку и прекращаем выполнение
    ac.error("Ошибка: ID машины не совпадает с 'lew1x_bmw_m2_g87_at_s2'")
    return -- Прекращаем выполнение скрипта
end

-- Ваш код здесь будет выполняться только если carID совпадает
-- Например:
ac.warn("Код успешно запущен для " .. carID)
--because this is specific to this car, I"m going to make a table that draws the gears quickly. This can be edited for future cars.

local blinkTimer = 0
local blinkState = false

local gearT = {
    [-1] = "R",
    [0] = "N",
    [1] = "1D",
    [2] = "2D",
    [3] = "3D",
    [4] = "4D",
    [5] = "5D",
    [6] = "6D",
    [7] = "7D",
    [8] = "8D"
    
}

local Icons = {
    ["EML"] = "assets/icons/EML_ON.png",
    ["ABS"] = "assets/icons/ABS_ON.png",
    ["ESC"] = "assets/icons/m2.dds",
    ["ILEFT"] = "assets/icons/left.dds",
    ["IRIGHT"] = "assets/icons/right.dds",
    ["LIGHT_HIGHBEAM"] = "assets/icons/high.dds",
    ["LIGHT_PARKING"] = "assets/icons/LIGHT_PARKING.png",
    ["SPEEDLIMIT"] = "assets/icons/speedlimit2.png"
}

local timer = 2.0

local indicatorActive
setInterval(function() indicatorActive = not indicatorActive end, 1/2.6)

local carRPM = 0
local carSpeed = 0
local carFUEL = 0
local carTEMP = 0

local rpmframe
local rpmmaxframe = 200
local rpmposition = vec2(2137,97)
local rpmsize = vec2(600,800):scale(1)

local speedframe
local speedmaxframe = 200
local speedsize  = vec2(600,800):scale(1)
local speedposition = vec2(153,97)

local fuelframe
local fuelmaxframe = 50
local fuelsize  = vec2(210,260):scale(1)
local fuelposition = vec2(534,595)

local oilframe
local oilmaxframe = 50
local oilsize  = vec2(210,260):scale(1)
local oilposition = vec2(2199,595)
 
local rpmStartUp = 0
local SpeedStartUp = 0
local FuelStartUp = 0
local OilStartUp = 0
local dashReady = false
local counter = 0
local temptyre0, temptyre1, temptyre2, temptyre3 ,pressuretyre0 , pressuretyre1, pressuretyre2, pressuretyre3 = 0, 0, 0, 0, 0, 0, 0, 0

function update(dt)
    ui.setAsynchronousImagesLoading(true)

    if rpmStartUp < rpmmaxframe then
        rpmStartUp = rpmStartUp + 1
        ui.drawImage("./assets/frames_rpm/rpm".. rpmStartUp ..".dds", rpmposition, vec2(rpmposition.x+rpmsize.x, rpmposition.y+rpmsize.y))
    end

    if SpeedStartUp < speedmaxframe then 
        SpeedStartUp = SpeedStartUp + 1
        ui.drawImage("./assets/frames_speed/speed".. SpeedStartUp ..".dds", speedposition, vec2(speedposition.x+speedsize.x, speedposition.y+speedsize.y)) 
    end

    if FuelStartUp < fuelmaxframe then 
        FuelStartUp = FuelStartUp + 1
        ui.drawImage("./assets/frames_fuel/fuel".. FuelStartUp ..".dds", fuelposition, vec2(fuelposition.x+fuelsize.x, fuelposition.y+fuelsize.y)) 
    end

    if OilStartUp < oilmaxframe then 
        OilStartUp = OilStartUp + 1
        ui.drawImage("./assets/frames_temp/temp".. OilStartUp ..".dds", oilposition, vec2(oilposition.x+oilsize.x, oilposition.y+oilsize.y)) 
    end

    if timer >= 0 then
        timer = timer  - 0.025 - dt 
	else
	timer = 2 - dt
    end

    local time = string.format("%02d:%02d",sim.timeHours,sim.timeMinutes)
    local temp = "+" .. math.floor(sim.ambientTemperature)
    local distance = car.fuel * 1.228856
    local rounded_distance = math.floor(distance + 0.5)  -- Округление до ближайшего целого

	
	     counter = counter + dt

if counter >= 2 then
    temptyre0 = math.floor(ac.getCar(0).wheels[0].tyreCoreTemperature)
    temptyre1 = math.floor(ac.getCar(0).wheels[1].tyreCoreTemperature)
    temptyre2 = math.floor(ac.getCar(0).wheels[2].tyreCoreTemperature)
    temptyre3 = math.floor(ac.getCar(0).wheels[3].tyreCoreTemperature)
    pressuretyre0 = math.floor(ac.getCar(0).wheels[0].tyrePressure)
    pressuretyre1 = math.floor(ac.getCar(0).wheels[1].tyrePressure)
    pressuretyre2 = math.floor(ac.getCar(0).wheels[2].tyrePressure)
    pressuretyre3 = math.floor(ac.getCar(0).wheels[3].tyrePressure)
    counter = 0
end

    
	ui.setAsynchronousImagesLoading(false)

	--rpmframe = math.floor(0.0404*car.rpm)
	carRPM = math.applyLag(carRPM, car.rpm, 0.8, dt)

	rpmframe = math.min(rpmmaxframe, (rpmmaxframe/8000)*carRPM+10)
	rpmframe = math.floor(rpmframe)
	ui.drawImage("./assets/frames_rpm/rpm"..rpmframe..".dds", rpmposition, vec2(rpmposition.x+rpmsize.x, rpmposition.y+rpmsize.y))


    function getSpeedFrame(speedKmh)
    local points = {
        {0, 0},
        {30, 27},
        {60, 53},
        {90, 77},
        {120, 103},
        {150, 127},
        {210, 151},
        {270, 175},
        {330, 199},
    }
    
    for i = 1, #points - 1 do
        local x1, y1 = table.unpack(points[i])
        local x2, y2 = table.unpack(points[i+1])
        
        -- Если speedKmh между x1 и x2, используем линейную интерполяцию
        if speedKmh >= x1 and speedKmh <= x2 then
            local m = (y2 - y1) / (x2 - x1)
            local b = y1 - m * x1
            return m * speedKmh + b
        end
    end
    
    -- Если speedKmh выходит за пределы, возвращаем ближайшее значение
    if speedKmh < points[1][1] then
        return points[1][2]
    else
        return points[#points][2]
    end
end

speedframe = getSpeedFrame(car.speedKmh)

-- Обеспечиваем, что speedframe не выходит за границы [0, 299]
speedframe = math.max(0, math.min(299, speedframe))


	ui.drawImage("./assets/frames_speed/speed" .. math.min(speedmaxframe, math.floor(speedframe)) .. ".dds", speedposition, vec2(speedposition.x+speedsize.x, speedposition.y+speedsize.y))

    function getOilFrame(oilTemperature)
        local points = {
            {50, 0},
            {150, 49},
        }
        
        for i = 1, #points - 1 do
            local x1, y1 = table.unpack(points[i])
            local x2, y2 = table.unpack(points[i+1])
            
            -- Если oilTemperature между x1 и x2, используем линейную интерполяцию
            if oilTemperature >= x1 and oilTemperature <= x2 then
                local m = (y2 - y1) / (x2 - x1)
                local b = y1 - m * x1
                return m * oilTemperature + b
            end
        end
        
        -- Если oilTemperature выходит за пределы, возвращаем ближайшее значение
        if oilTemperature < points[1][1] then
            return points[1][2]
        else
            return points[#points][2]
        end
    end
    
    oilframe = getOilFrame(car.oilTemperature)

        ui.drawImage("./assets/frames_temp/temp" .. math.min(oilmaxframe, math.floor(oilframe)) .. ".dds", oilposition, vec2(oilposition.x+oilsize.x, oilposition.y+oilsize.y))
    

--fuelframe = math.floor(0.0404*car.fuel)
carFUEL = math.applyLag(carFUEL, car.fuel, 0.8, dt)

fuelframe = math.min(fuelmaxframe, (fuelmaxframe/52)*carFUEL)
fuelframe = math.floor(fuelframe)
ui.drawImage("./assets/frames_fuel/fuel"..fuelframe..".dds", fuelposition, vec2(fuelposition.x+fuelsize.x, fuelposition.y+fuelsize.y))


    ----- Dash loading thing -----
    if dashReady == false then
        if rpmStartUp == rpmmaxframe and SpeedStartUp == speedmaxframe and fuelmaxframe == FuelStartUp and oilmaxframe == OilStartUp then   
            display.text{
            text = "DASH LOADED",
            pos = vec2(1275,100),
            letter = vec2(20, 40):scale(2),
            font = "fonts/bmw_g_font",
            color = rgbm.colors.white,
            alignment = 0,
            width = 1000,
            spacing = 0
            }
            setTimeout(function () dashReady = true end, 2.5)            
        else
            display.text{
                text = "DASH LOADING",
                pos = vec2(725,100),
                letter = vec2(20, 40):scale(2),
                font = "fonts/bmw_g_font",
                color = rgbm.colors.white,
                alignment = 1,
                width = 1000,
                spacing = 0
            }
   
        end
    end


    ----- speed -----
    display.text {
        text = string.format("%2d", math.round(car.speedKmh)),
        pos = vec2(585,385),
        color = rgbm(1,1,1,1),
        letter = vec2(105, 180),
        font = "fonts/bmw_g_font",
        width = 250,
        alignment = 1
    }
   ----- tyres -----
    --temp--
    display.text {
        text = temptyre0,
        pos = vec2(1195,390),
        color = rgbm(1,1,1,1),
        letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1
    }



        display.text {
        text = temptyre2,
        pos = vec2(1195,670),
        color = rgbm(1,1,1,1),
        letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1
    }



        display.text {
        text = temptyre1,
        pos = vec2(1680,390),
        color = rgbm(1,1,1,1),
        letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1
    }



        display.text {
        text = temptyre3,
        pos = vec2(1680,670),
        color = rgbm(1,1,1,1),
       letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1
    }


    --pressure--
    display.text {
        text = pressuretyre0,
        pos = vec2(1195,340),
        color = rgbm(1,1,1,1),
        letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1
    }



        display.text {
        text = pressuretyre2,
        pos = vec2(1195,620),
        color = rgbm(1,1,1,1),
        letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1
    }



        display.text {
        text = pressuretyre1,
        pos = vec2(1680,340),
        color = rgbm(1,1,1,1),
        letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1
    }



        display.text {
        text = pressuretyre3,
        pos = vec2(1680,620),
        color = rgbm(1,1,1,1),
       letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1


        
    }
        --dot--

        display.text {
        text = ".",
        pos = vec2(1702,340),
        color = rgbm(1,1,1,1),
       letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1
    }
        display.text {
        text = ".",
        pos = vec2(1702,620),
        color = rgbm(1,1,1,1),
       letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1



    }
        --dot--

        display.text {
        text = ".",
        pos = vec2(1217,340),
        color = rgbm(1,1,1,1),
       letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1
    }
        display.text {
        text = ".",
        pos = vec2(1217,620),
        color = rgbm(1,1,1,1),
       letter = vec2(40, 50),
        font = "fonts/bmw_g_font",
        width = 0,
        alignment = 1



        
    }
	
    ----- draw the current gear but looking in the table created at the start. Much faster than before -----

-- Получаем строку передачи из таблицы gearT
local gearStr = gearT[car.gear]

if gearStr then
    -- Пытаемся найти шаблон: цифры, затем буква (например, "3D")
    local num, letter = gearStr:match("^(%d+)(%a)$")
    if num and letter then
        -- Рисуем цифру серым цветом
        display.text {
            text = num,
            pos = vec2(2010,385),
            color = rgbm(0.5, 0.5, 0.5, 1),  -- серый цвет
            letter = vec2(135, 180),
            font = "fonts/bmw_g_font",
            width = 200,
            alignment = 1
        }
        -- Рисуем букву (например, "D") белым цветом.
        -- Положение по X нужно сдвинуть вправо относительно позиции цифры.
        local offsetX = 70  -- подберите значение сдвига под нужный вам шрифт и размеры
        display.text {
            text = letter,
            pos = vec2(2065 + offsetX,385),
            color = rgbm(1, 1, 1, 1),  -- белый цвет
            letter = vec2(135, 180),
            font = "fonts/bmw_g_font",
            width = 200,
            alignment = 1
        }
    else
        -- Если строка не соответствует шаблону (например, "R" или "N"), выводим её целиком белым цветом
        display.text {
            text = gearStr,
            pos = vec2(2065,385),
            color = rgbm(1, 1, 1, 1),
            letter = vec2(135, 180),
            font = "fonts/bmw_g_font",
            width = 200,
            alignment = 1
        }
    end
end


        display.text {
        text = temp,
        pos = vec2(2640,950),
        color = rgbm(1,1,1,1),
        letter = vec2(40, 70),
        font = "fonts/bmw_g_font",
        width = 120,
        alignment = 1
    }




    
        display.text {
            text = rounded_distance,
            pos = vec2(605,945),
            color = rgbm(1,1,1,1),
        letter = vec2(40, 70),
            font = "fonts/bmw_g_font",
            width = 120,
            alignment = 1
        }


        display.text {
        text = time,
        pos = vec2(180,945),
        color = rgbm(1,1,1,1),
        letter = vec2(40, 70),
        font = "fonts/bmw_g_font",
        width = 120,
        alignment = 1
        }

        display.image {
        image = "/assets/icons/drl.dds",
        pos = vec2(60, 477),
        size = vec2(90,90),
        uvStart = vec2(0,0),
        uvEnd = vec2(1,1)
        }
        
    if car.headlightsActive then

        display.image {
        image = "/assets/icons/low.dds",
        pos = vec2(60, 547),
        size = vec2(90,90),
        uvStart = vec2(0,0),
        uvEnd = vec2(1,1)
        }
            
    end

    if car.handbrake == 1 then

        display.image {
        image = "/assets/icons/handbrake.dds",
        pos = vec2(60, 807),
        size = vec2(90,90),
        uvStart = vec2(0,0),
        uvEnd = vec2(1,1)
        }
            
    end

    if not car.lowBeams and car.headlightsActive then

        display.image {
        image = "/assets/icons/high.dds",
        pos = vec2(60, 627),
        size = vec2(90,90),
        uvStart = vec2(0,0),
        uvEnd = vec2(1,1)
        }
            
    end

    if car.gear > 0 then

	    display.image {
        image = "/assets/icons/idk.dds",
        pos = vec2(2320, 449),
        size = vec2(80,80),
        uvStart = vec2(0,0),
        uvEnd = vec2(1,1)
        }
    end

    if car.gear <= 0 then

	    display.image {
        image = "/assets/icons/idk.dds",
        pos = vec2(2260, 449),
        size = vec2(80,80),
        uvStart = vec2(0,0),
        uvEnd = vec2(1,1)
        }
    end

    if timer > 1 and car.turningRightLights == true then

        display.image {
            image = "/assets/icons/right.dds",
            pos = vec2(1822,78),
            size = vec2(100,100),
            uvStart = vec2(0, 0),
            uvEnd = vec2(1, 1)
        }
    end

    if timer > 1 and car.turningLeftLights == true then

        display.image {
            image = "/assets/icons/left.dds",
            pos = vec2(1044,78),
            size = vec2(100,100),
            uvStart = vec2(0, 0),
            uvEnd = vec2(1, 1)
        }
    end

    if car.tractionControlMode == 0 then

        display.image {
            image = "/assets/icons/m2.dds",
            pos = vec2(2234, 310),
            size = vec2(115,110),
            uvStart = vec2(0,0),
            uvEnd = vec2(1,1)
       }
        
       end

       if car.tractionControlMode == 2 then

        display.image {
            image = "/assets/icons/m1.dds",
            pos = vec2(2234, 310),
            size = vec2(115,110),
            uvStart = vec2(0,0),
            uvEnd = vec2(1,1)
       }
        
       end

            -- Обновляем таймер мигания, если обороты больше 7000
        if carRPM >= 7000 then
            blinkTimer = blinkTimer + dt
            if blinkTimer >= 0.25 then
                blinkState = not blinkState
                blinkTimer = 0
            end
        end

        -- Обновляем таймер мигания, если обороты больше 7000
        if carRPM >= 7000 then
            blinkTimer = blinkTimer + dt
            if blinkTimer >= 0.35 then
                blinkState = not blinkState
                blinkTimer = 0
            end
        end

        -- Определяем текстуру отсечки в зависимости от оборотов
        local otsechkaTexture = ""
        if carRPM >= 5000 and carRPM < 7000 then
            local index = math.floor((carRPM - 5000) / 250)
            otsechkaTexture = "./assets/otsechka/otsechka_" .. index .. ".dds"
        elseif carRPM >= 7000 then
            if blinkState then
                otsechkaTexture = "./assets/otsechka/otsechka_8.dds"
            else
                otsechkaTexture = ""
            end
        end

        -- Отображаем текстуру отсечки, если она задана
        if otsechkaTexture ~= "" then
            ui.drawImage(otsechkaTexture, vec2(531, 52), vec2(531 + 1899, 52 + 42))
        end
end

