local playAnim = false
local phoneProp = 0
local phoneModel = Config.PhoneModel


-- Item checks to return whether or not the client has a phone or not
local function HasPhone()
    return QBCore.Functions.HasItem("phone")
end


-- Loads the animdict so we can execute it on the ped
local function loadAnimDict(dict)
    RequestAnimDict(dict)

    while not HasAnimDictLoaded(dict) do
        Wait(0)
    end
end

local function DeletePhone()
	if phoneProp ~= 0 then
		DeleteObject(phoneProp)
		phoneProp = 0
	end
end

local function NewPropWhoDis()
	DeletePhone()
	RequestModel(phoneModel)
	while not HasModelLoaded(phoneModel) do
		Wait(1)
	end
	phoneProp = CreateObject(phoneModel, 1.0, 1.0, 1.0, 1, 1, 0)

	local bone = GetPedBoneIndex(PlayerPedId(), 28422)
	if phoneModel == Config.PhoneModel then
		AttachEntityToEntity(phoneProp, PlayerPedId(), bone, 0.0, 0.0, 0.0, 15.0, 0.0, 0.0, 1, 1, 0, 0, 2, 1)
	else
		AttachEntityToEntity(phoneProp, PlayerPedId(), bone, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1, 1, 0, 0, 2, 1)
	end
end

-- Does the actual animation of the animation when calling 911
local function PhoneCallAnim()
    loadAnimDict("cellphone@")
    local ped = PlayerPedId()
    CreateThread(function()
        NewPropWhoDis()
        playAnim = true
        while playAnim do
            if not IsEntityPlayingAnim(ped, "cellphone@", 'cellphone_text_to_call', 3) then
                TaskPlayAnim(ped, "cellphone@", 'cellphone_text_to_call', 3.0, 3.0, -1, 50, 0, false, false, false)
            end
            Wait(100)
        end
    end)
end


-- Regular 911 call that goes straight to the Police
RegisterCommand('114', function(source, args, rawCommand)
    local msg = rawCommand:sub(5)
    if string.len(msg) > 0 then
        if not exports['qb-policejob']:IsHandcuffed() then
            if HasPhone() then
                PhoneCallAnim()
                Wait(math.random(3,8) * 1000)
                playAnim = false
                local plyData = QBCore.Functions.GetPlayerData()
                local currentPos = GetEntityCoords(PlayerPedId())
                local locationInfo = getStreetandZone(currentPos)
                local gender = GetPedGender()
                TriggerServerEvent("dispatch:server:notify",{
                    dispatchcodename = "114call", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
                    dispatchCode = "114",
                    firstStreet = locationInfo,
                    priority = 2, -- priority
                    name = plyData.charinfo.firstname:sub(1,1):upper()..plyData.charinfo.firstname:sub(2).. " ".. plyData.charinfo.lastname:sub(1,1):upper()..plyData.charinfo.lastname:sub(2),
                    number = plyData.charinfo.phone,
                    origin = {
                        x = currentPos.x,
                        y = currentPos.y,
                        z = currentPos.z
                    },
                    dispatchMessage = "Ingående opkald", -- message
                    information = msg,
                    job = {"police", "ambulance"} -- jobs that will get the alerts
                })
                Wait(1000)
                DeletePhone()
                StopEntityAnim(PlayerPedId(), 'cellphone_text_to_call', "cellphone@", 3)
            else
                QBCore.Functions.Notify("Du kan ikke ringe uden en telefon!", "error", 4500)
            end
        else
            QBCore.Functions.Notify("Du kan ikke ringe når du er i håndjern..", "error", 4500)
        end
    else
        QBCore.Functions.Notify('Angiv en årsag efter 114', "success")
    end
end, false)

RegisterCommand('114a', function(source, args, rawCommand)
    local msg = rawCommand:sub(5)
    if string.len(msg) > 0 then
        if not exports['qb-policejob']:IsHandcuffed() then
            if HasPhone() then
                PhoneCallAnim()
                Wait(math.random(3,8) * 1000)
                playAnim = false
                local plyData = QBCore.Functions.GetPlayerData()
                local currentPos = GetEntityCoords(PlayerPedId())
                local locationInfo = getStreetandZone(currentPos)
                local gender = GetPedGender()
                TriggerServerEvent("dispatch:server:notify",{
                    dispatchcodename = "114call", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
                    dispatchCode = "114",
                    firstStreet = locationInfo,
                    priority = 2, -- priority
                    name = "Anonym",
                    number = "Skjult Nummer",
                    origin = {
                        x = currentPos.x,
                        y = currentPos.y,
                        z = currentPos.z
                    },
                    dispatchMessage = "Ingående anonymt opkald", -- message
                    information = msg,
                    job = {"police", "ambulance"} -- jobs that will get the alerts
                })
                Wait(1000)
                DeletePhone()
                StopEntityAnim(PlayerPedId(), 'cellphone_text_to_call', "cellphone@", 3)
            else
                QBCore.Functions.Notify("Du kan ikke ringe uden en telefon!", "error", 4500)
            end
        else
            QBCore.Functions.Notify("Du kan ikke ringe når du er i håndjern..", "error", 4500)
        end
    else
        QBCore.Functions.Notify('Angiv en årsag efter 114', "success")
    end
end, false)

-- Regular 311 call that goes straight to the Police
RegisterCommand('112', function(source, args, rawCommand)
    local msg = rawCommand:sub(5)
    if string.len(msg) > 0 then
        if not exports['qb-policejob']:IsHandcuffed() then
            if HasPhone() then
                PhoneCallAnim()
                Wait(math.random(3,8) * 1000)
                playAnim = false
                local plyData = QBCore.Functions.GetPlayerData()
                local currentPos = GetEntityCoords(PlayerPedId())
                local locationInfo = getStreetandZone(currentPos)
                local gender = GetPedGender()
                TriggerServerEvent("dispatch:server:notify",{
                    dispatchcodename = "112call", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
                    dispatchCode = "112",
                    firstStreet = locationInfo,
                    priority = 2, -- priority
                    name = plyData.charinfo.firstname:sub(1,1):upper()..plyData.charinfo.firstname:sub(2).. " ".. plyData.charinfo.lastname:sub(1,1):upper()..plyData.charinfo.lastname:sub(2),
                    number = plyData.charinfo.phone,
                    origin = {
                        x = currentPos.x,
                        y = currentPos.y,
                        z = currentPos.z
                    },
                    dispatchMessage = "Ingående opkald", -- message
                    information = msg,
                    job = {"police", "ambulance"} -- jobs that will get the alerts
                })
                Wait(1000)
                DeletePhone()
                StopEntityAnim(PlayerPedId(), 'cellphone_text_to_call', "cellphone@", 3)
            else
                QBCore.Functions.Notify("Du kan ikke ringe uden en telefon!", "error", 4500)
            end
        else
            QBCore.Functions.Notify("Du kan ikke ringe når du er i håndjern..", "error", 4500)
        end
    else
        QBCore.Functions.Notify('Angiv en årsag efter 112', "success")
    end
end, false)

-- Regular 311 call that goes straight to the Police
RegisterCommand('112a', function(source, args, rawCommand)
    local msg = rawCommand:sub(5)
    if string.len(msg) > 0 then
        if not exports['qb-policejob']:IsHandcuffed() then
            if HasPhone() then
                PhoneCallAnim()
                Wait(math.random(3,8) * 1000)
                playAnim = false
                local plyData = QBCore.Functions.GetPlayerData()
                local currentPos = GetEntityCoords(PlayerPedId())
                local locationInfo = getStreetandZone(currentPos)
                local gender = GetPedGender()
                TriggerServerEvent("dispatch:server:notify",{
                    dispatchcodename = "112call", -- has to match the codes in sv_dispatchcodes.lua so that it generates the right blip
                    dispatchCode = "112",
                    firstStreet = locationInfo,
                    priority = 2, -- priority
                    name = "Anonym",
                    number = "Skjult Nummer",
                    origin = {
                        x = currentPos.x,
                        y = currentPos.y,
                        z = currentPos.z
                    },
                    dispatchMessage = "Ingående anonymt opkald", -- message
                    information = msg,
                    job = {"police", "ambulance"} -- jobs that will get the alerts
                })
                Wait(1000)
                DeletePhone()
                StopEntityAnim(PlayerPedId(), 'cellphone_text_to_call', "cellphone@", 3)
            else
                QBCore.Functions.Notify("Du kan ikke ringe uden en telefon!", "error", 4500)
            end
        else
            QBCore.Functions.Notify("Du kan ikke ringe når du er i håndjern..", "error", 4500)
        end
    else
        QBCore.Functions.Notify('Angiv en årsag efter 112a', "success")
    end
end, false)


Citizen.CreateThread(function()
    TriggerEvent('chat:addSuggestion', '/114', 'Send en besked til politiet.', {{ name="besked", help="Besked til politiet."}})
    TriggerEvent('chat:addSuggestion', '/114a', 'Send en anonym besked til politiet.', {{ name="besked", help="Anonym besked til politiet."}})
    TriggerEvent('chat:addSuggestion', '/112', 'Send en besked til EMS.', {{ name="besked", help="Besked til EMS."}})
    TriggerEvent('chat:addSuggestion', '/112a', 'Send en anonym besked til EMS.', {{ name="besked", help="Anonym besked til EMS."}})
end)