vehicletype = GetStringParam("vehicletype")
spec_function = GetBoolParam("spec_function")
spec_function_sound = GetStringParam("spec_sound")

function init()
    seat = FindShape("seat")
    leg = FindShapes("leg")
    leg1joint = GetShapeJoints(leg[1])[1]
    leg2joint = GetShapeJoints(leg[2])[1]
    min, max = GetJointLimits(leg1joint)
    vehicle = FindVehicle("EVF")
    downpressed = 0

    attachcooldown = 1

    if vehicletype == "truck" then
        attachloc = FindLocation("attach")
        attachlocpos = GetLocationTransform(attachloc).pos
    else
        attachloc = FindTrigger("trailerattachtrigger")
        attachlocpos = GetTriggerTransform(attachloc).pos
    end

    vehicletransform = GetVehicleTransform(vehicle)
    localpos = TransformToLocalPoint(vehicletransform, attachlocpos)

    SetJointMotorTarget(leg1joint, min, 1)
    SetJointMotorTarget(leg2joint, min, 1)

    if vehicletype == "truck" then
        clunk_in = LoadSound("MOD/extra-scripts/snd/clunk2.ogg")
        clunk_out = LoadSound("MOD/extra-scripts/snd/clunk1.ogg")

        brake = FindLights("Brake")
        reverse = FindLights("Reverse")
    end
    spec_min = {}
    spec_max = {}
    if vehicletype == "trailer" then
        if spec_function then
            hyd_loop = LoadLoop(spec_function_sound)
            spec_function_joints = FindJoints("spec_function")
            for i = 1, #spec_function_joints do
                spec_min[i], spec_max[i] = GetJointLimits(spec_function_joints[i])
            end
            SetTag(GetVehicleBody(vehicle), "spec-")
        end
    end
end

function tick()
    if vehicletype == "truck" then
        if GetPlayerVehicle() == vehicle and not IsShapeBroken(seat) then
            vehicletransform = GetVehicleTransform(vehicle)
            worldattachpos = TransformToParentPoint(vehicletransform, localpos)
            trailertriggers = FindTriggers("trailerattachtrigger", true)
            for i = 1, #trailertriggers do
                if IsShapeInTrigger(trailertriggers[i], seat) then
                    InTrigger = true
                    SetTag(seat, "InTrigger", i)
                    if InputPressed("T") and not HasTag(seat, "Attached") and attachcooldown == 1 and not IsShapeBroken(seat) then
                        trailer = FindVehicles("trailer", true)[i]
                        trailerbody = GetVehicleBody(trailer)
                        SetTag(trailerbody, "Attached")
                        SetTag(seat, "Attached")
                        trailertransform = GetBodyTransform(trailerbody)
                        trailertriggertransform = GetTriggerTransform(trailertriggers[i]).pos
                        newposraw = VecSub(worldattachpos, trailertriggertransform)
                        newpos = VecAdd(trailertransform.pos, newposraw)
                        SetBodyTransform(trailerbody, Transform(Vec(newpos[1], trailertransform.pos[2], newpos[3]), trailertransform.rot))
                        Spawn("<joint type='hinge' rotspring='0' rot='90 0 0' size='0.2'/>", Transform(worldattachpos), false, true)
                        attachcooldown = 0
                        SetValue("attachcooldown", 1, "linear", 1)
                        PlaySound(clunk_in, worldattachpos, 0.15)
                        RemoveTag(trailerbody, "R")
                    end
                else          
                    if GetTagValue(seat, "InTrigger") == tostring(i) then
                        InTrigger = false
                        RemoveTag(seat, "InTrigger")
                    end
                end
            end
            if HasTag(seat, "Attached") then
                if InputDown("handbrake") then
                    SetTag(trailerbody, "Handbrake")
                else
                    RemoveTag(trailerbody, "Handbrake")
                end
                if IsLightActive(brake[1]) or IsLightActive(reverse[1]) or IsLightActive(brake[2]) or IsLightActive(reverse[2]) then
                    if not InputDown("handbrake") then
                        SetTag(trailerbody, "R")
                    end
                else
                    RemoveTag(trailerbody, "R")
                end
                if InputPressed("T") and attachcooldown == 1 then
                    attachcooldown = 0
                    SetValue("attachcooldown", 1, "linear", 1)
                    DetachJointFromShape(GetShapeJoints(seat)[1], seat)
                    RemoveTag(seat, "Attached")
                    RemoveTag(trailerbody, "Attached")
                    trailerclear()
                    PlaySound(clunk_out, worldattachpos, 0.15)
                end
                if InputPressed("H") then
                    if HasTag(trailerbody, "spec-") then
                        RemoveTag(trailerbody, "spec-")
                        SetTag(trailerbody, "spec+")
                    elseif HasTag(trailerbody, "spec+") then
                        RemoveTag(trailerbody, "spec+")
                        SetTag(trailerbody, "spec-")
                    end
                end
            end
            SetTag(trailerbody, "Drive")
        else
            RemoveTag(trailerbody, "Drive")
            RemoveTag(trailerbody, "R")
        end
        if IsShapeBroken(seat) and HasTag(seat, "Attached") then
            RemoveTag(seat, "Attached")
            RemoveTag(trailerbody, "Attached")
            DetachJointFromShape(GetShapeJoints(seat)[1], seat)
            trailerclear()
            PlaySound(clunk_out, worldattachpos, 0.15)
        end
    end

    if vehicletype == "trailer" then
        if HasTag(GetVehicleBody(vehicle), "R") then
            drivecontrol = -0.1
        else
            drivecontrol = 0.1
        end
        if HasTag(GetVehicleBody(vehicle), "Handbrake") then
            handbrakecontrol = true
        else
            handbrakecontrol = false
        end
        if HasTag(GetVehicleBody(vehicle), "Drive") then
            DriveVehicle(vehicle, drivecontrol, 0, handbrakecontrol)
        end
    end
end

function update()
    initactivate()
    if vehicletype == "trailer" then
        vehicletransform = GetVehicleTransform(vehicle)
        worldattachpos = TransformToParentPoint(vehicletransform, localpos)
        SetTriggerTransform(attachloc, Transform(worldattachpos, QuatEuler(0,0,0)))

        if HasTag(GetVehicleBody(vehicle), "Attached") then
            SetJointMotorTarget(leg1joint, max, 1)
            SetJointMotorTarget(leg2joint, max, 1)
            if (spec_function) then
                if HasTag(GetVehicleBody(vehicle), "spec-") then
                    for i=1, #spec_function_joints do
                        SetJointMotorTarget(spec_function_joints[i], spec_min[i], 0.1)
                    end
                end
                if HasTag(GetVehicleBody(vehicle), "spec+") then
                    for i=1, #spec_function_joints do
                        SetJointMotorTarget(spec_function_joints[i], spec_max[i], 0.1)
                    end
                end
                for i=1, #spec_function_joints do
                    if GetJointMovement(spec_function_joints[i]) > spec_min[i]+0.1 and GetJointMovement(spec_function_joints[i]) < spec_max[i]-0.1 and not IsJointBroken(spec_function_joints[i]) then
                        PlayLoop(hyd_loop, GetBodyTransform(GetVehicleBody(vehicle)).pos, 0.3)
                    end
                end
            end
        else
            SetJointMotorTarget(leg1joint, min, 1)
            SetJointMotorTarget(leg2joint, min, 1)
        end
    end
end

function initactivate()
    if not bodyactive and vehicletype == "trailer" then
        SetBodyActive(GetVehicleBody(vehicle), true)
        SetBodyActive(GetVehicleBody(vehicle), false)
        bodyactive = true
    end
end

function trailerclear()
    RemoveTag(trailerbody, "Drive")
    trailerbody = nil
    trailer = nil
    trailertransform = nil
    trailertriggertransform = nil
end

function draw()
    if GetPlayerVehicle() == vehicle and vehicletype == "truck" and not GetBool("hud.disable") then
        if InTrigger then
            UiPush()
                UiAlign("center middle")
                UiTranslate(UiCenter()-900, UiMiddle()+496)

                UiPush()
                    UiColor(0,0,0,0.5)
                    if HasTag(trailerbody, "spec+") or HasTag(trailerbody, "spec-") then
                        UiTranslate(95, -25)
                        UiImageBox("ui/common/box-solid-6.png", 260, 100, 6, 6)
                    else
                        UiTranslate(85, 0)
                        UiImageBox("ui/common/box-solid-6.png", 240, 50, 6, 6)
                    end
                UiPop()

                UiFont("regular.ttf", 30)
                UiText("T")
                if HasTag(trailerbody, "spec+") or HasTag(trailerbody, "spec-") then
                    UiPush()
                        UiTranslate(0, -50)
                        UiText("H")
                    UiPop()
                end
                UiTranslate(100, 2)
                UiColorFilter(1, 1, 1, 0.7)
                if not HasTag(seat, "Attached") then
                    UiText("Attach trailer")
                else
                    UiText("Detach trailer")
                    if HasTag(trailerbody, "spec+") or HasTag(trailerbody, "spec-") then
                        UiTranslate(10, -50)
                        UiText("Trailer function")
                    end
                end
            UiPop()
        end
    end
end