AGanim = AGanim or {}

local pl = FindMetaTable("Player")
local AnimationTable = {
    [1] = {name = "Помахать руками", anim = "rp_wave", loop = false},
    [2] = {name = "Помахать рукой", anim = "gesture_wave_original", loop = false},
    [3] = {name = "Показать пальцем вперед", anim = "rp_point", loop = false},
    [4] = {name = "Показать пальцем назад", anim = "rp_point_back", loop = false},
    [5] = {name = "Поправить галстук", anim = "menu_gman", loop = false},
    [6] = {name = "Приседания", anim = "rp_sport1_loop", loop = true},
    [7] = {name = "Отжимания", anim = "rp_sport2_loop", loop = true},
    [8] = {name = "Подьем корпуса", anim = "rp_sport3_loop", loop = true},
    [9] = {name = "Берпи", anim = "rp_sport4_loop", loop = true},
    [10] = {name = "Стоять злобно", anim = "rp_angry_loop", loop = true},
    [11] = {name = "Стоять напуганно", anim = "idle_all_scared", loop = true},
    [12] = {name = "Стоять, сложив руки", anim = "pose_standing_01", loop = true},
    [13] = {name = "Стоять, руки на поясе", anim = "pose_standing_02", loop = true},
    [14] = {name = "Стоять, держась за пояс", anim = "rp_cop_idle", loop = true},
    [15] = {name = "Сидеть, положив руку на колено", anim = "pose_ducking_01", loop = true},
    [16] = {name = "Сидеть в позе лотаса", anim = "pose_ducking_02", loop = true},
    [17] = {name = "Сидеть в сонном состоянии", anim = "rp_sit_loop", loop = true},
    [18] = {name = "Лежать в плохом состоянии", anim = "rp_injured_loop", loop = true},
    [19] = {name = "Танец 1", anim = "rp_dance1_loop", loop = true},
    [20] = {name = "Танец 2", anim = "rp_dance2_loop", loop = true},
    [21] = {name = "Танец 3", anim = "rp_dance3_loop", loop = true},
    [22] = {name = "Танец 4", anim = "taunt_dance_base", loop = true},
    [23] = {name = "Показать согласие", anim = "gesture_agree_original", loop = false},
    [24] = {name = "Показать несогласие", anim = "gesture_disagree_original", loop = false},
    [25] = {name = "Позвать с собой", anim = "gesture_becon_original", loop = false},
    [26] = {name = "Поклонится", anim = "gesture_bow_original", loop = false},
    [27] = {name = "Отдать честь", anim = "gesture_salute_original", loop = false},
    [28] = {name = "Пить кофе", anim = "rp_drinking", loop = true, prop = {model = "models/props_junk/garbage_coffeemug001a.mdl", spawnfunc = function(mod, ent)
        local att = ent:LookupAttachment("anim_attachment_RH")
        local lvec = Vector(1,0,1)

        timer.Create("WhileThatPropExist"..ent:EntIndex(), 0, 0, function()
            if IsValid(mod) then
                local tab = ent:GetAttachment(att)
                mod:SetPos(tab.Pos+tab.Ang:Up()*lvec.z+tab.Ang:Right()*lvec.y+tab.Ang:Forward()*lvec.x)
                mod:SetAngles(tab.Ang)
                if !IsValid(ent) or !ent:Alive() then
                    timer.Remove("WhileThatPropExist"..ent:EntIndex())
                    mod:Remove()
                end
            else
                timer.Remove("WhileThatPropExist"..ent:EntIndex())
            end
        end)
    end}},
    [29] = {name = "Смотреть на обьект, сидя", anim = "rp_medic_idle", loop = true},
    [30] = {name = "Записывать в блокнот", anim = "rp_writing", loop = true, prop = {model = "models/props_lab/clipboard.mdl", spawnfunc = function(mod, ent)
        local att = ent:LookupAttachment("anim_attachment_RH")
        local lvec = Vector(2,-2,2)

        timer.Create("WhileThatPropExist"..ent:EntIndex(), 0, 0, function()
            if IsValid(mod) then
                local tab = ent:GetAttachment(att)
                mod:SetPos(tab.Pos+tab.Ang:Up()*lvec.z+tab.Ang:Right()*lvec.y+tab.Ang:Forward()*lvec.x)
                mod:SetAngles(tab.Ang+Angle(140,0,-100))
                if !IsValid(ent) or !ent:Alive() then
                    timer.Remove("WhileThatPropExist"..ent:EntIndex())
                    mod:Remove()
                end
            else
                timer.Remove("WhileThatPropExist"..ent:EntIndex())
            end
        end)
    end}},
    [31] = {name = "Спать", anim = "rp_sleep", loop = true},
    [32] = {name = "Воинское приветствие", anim = "rp_salute1", loop = true, loop_stop = true},
}

if SERVER then
    concommand.Add("rp_set_taunt", function(ply, cmd, args)
        local arg = tonumber(args[1])

        if arg > 0 and arg <= #AnimationTable then
            local tab = AnimationTable[arg]
            ply:SetTAnimation(tab.anim, !tab.loop, arg)
        end
    end)

    function pl:SetTAnimation(anim, autostop, id)
        self:SetNWString('TauntAnim', anim)
        self:SetNWFloat('TauntID', id)
        self:SetNWFloat('TAnimDelay', select(2, self:LookupSequence(anim)))
        self:SetNWFloat('TAnimStartTime', CurTime())
        self:SetCycle(0)

        local wep = self:GetActiveWeapon()
        if IsValid(wep) and anim != "" then
            self.TauntPreviousWeapon = wep:GetClass()
            self:SetActiveWeapon(nil)
        elseif anim == "" and isstring(self.TauntPreviousWeapon) then
            self:SelectWeapon(self.TauntPreviousWeapon)
            self.TauntPreviousWeapon = nil
        end

        if autostop then
            local delay = select(2, self:LookupSequence(anim))
            timer.Create("TauntAGRP"..self:EntIndex(), delay, 1, function()
                if !IsValid(self) then return end
    
                local anim2 = self:GetNWString('TauntAnim')
    
                if anim == anim2 then
                    self:SetTAnimation("")
                end
            end)
        end
    end

    hook.Add("PlayerSwitchWeapon", "rp_Taunt", function( ply, oldWeapon, newWeapon )
        local str = ply:GetNWString('TauntAnim')
        if str != "" then
            return true
        end
    end)

    hook.Add("Think", "rp_Taunt", function()
        local plytab = player.GetAll()
        for i=1,#plytab do
            local ply = plytab[i]
            local str = ply:GetNWString('TauntAnim')
            if str != "" and (ply:InVehicle() or !ply:Alive() or ply:WaterLevel() >= 2) then
                ply:SetTAnimation("")
            end
        end
    end)
else
    CreateConVar("rp_taunt_firstperson", 0, FCVAR_ARCHIVE, "", 0, 1)
    CreateConVar("rp_taunt_realistic_firstperson", 0, FCVAR_ARCHIVE, "", 0, 1)

    hook.Add("CalcView", "rp_TauntCam", function(ply, pos, angles, fov)
        local str = ply:GetNWString('TauntAnim')
        if str != "" then
            if GetConVar("rp_taunt_firstperson"):GetBool() then
                local att = ply:GetAttachment(ply:LookupAttachment('eyes'))
                local ang1 = angles
                if GetConVar("rp_taunt_realistic_firstperson"):GetBool() then
                    ang1 = att.Ang
                end
                local view = {
                    origin = att.Pos,
                    angles = ang1,
                    fov = fov,
                    drawviewer = true
                }
            
                return view
            else
                local view = {
                    origin = pos - ( angles:Forward() * 100 ),
                    angles = angles,
                    fov = fov,
                    drawviewer = true
                }
            
                return view
            end
        end
    end)

    hook.Add("HUDPaint", "rp_TauntCam", function()
        local ply = LocalPlayer()
        local str = ply:GetNWString('TauntAnim')
        if str != "" then
            draw.SimpleTextOutlined("Нажмите SHIFT, чтобы убрать анимацию.", "Trebuchet18", ScrW()/2, ScrH()-250, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, color_black)
        end
    end)

    function AGRP_OpenTauntMenu()
        local d = vgui.Create("DFrame")
        d:SetSize(200, 300)
        d:Center()
        d:SetTitle("Меню анимаций")
        d:MakePopup()

        local sc = vgui.Create("DScrollPanel", d)
        sc:Dock(FILL)

        local dc = sc:Add("DCheckBoxLabel")
        dc:SetText("Включить первое лицо?")
        dc:SetConVar("rp_taunt_firstperson")
        dc:Dock(TOP)
        dc:DockMargin(0, 0, 0, 5)
        
        local dc = sc:Add("DCheckBoxLabel")
        dc:SetText("Включить поворот глаз от анимации?")
        dc:SetConVar("rp_taunt_realistic_firstperson")
        dc:Dock(TOP)
        dc:DockMargin(0, 0, 0, 15)	
        
        for i=1, #AnimationTable do
            local tab = AnimationTable[i]
            local but = sc:Add("DButton")
            but:SetText(tab.name)
            but:Dock(TOP)
            but:DockMargin(0, 0, 0, 5)
            but.DoClick = function(self)
                RunConsoleCommand("rp_set_taunt", i)
            end
        end
    end

    concommand.Add("rp_taunt_menu", AGRP_OpenTauntMenu)
end

---SHARED PART

hook.Add("SetupMove", "rp_Taunt", function(ply, mvd, cmd)
    local str = ply:GetNWString('TauntAnim')
    if str != "" then
        mvd:SetMaxSpeed(1)
        mvd:SetMaxClientSpeed(1)
        if SERVER then
            if ply:KeyDown(IN_SPEED) then
                ply:SetTAnimation("")
            end
        end
    end
end)

hook.Add("CalcMainActivity", "rp_SVAnims", function(ply, vel)
    local str = ply:GetNWString('TauntAnim')
    local num = ply:GetNWFloat('TAnimDelay')
    local id = ply:GetNWFloat('TauntID')
    local st = ply:GetNWFloat('TAnimStartTime')
    if str != "" and ply:Alive() then
        local ls = AnimationTable[id].loop_stop
        if ply:GetCycle() >= 1 then
            if not ls then
                ply:SetCycle(0)
                if SERVER then
                    ply:SetNWFloat('TAnimStartTime', CurTime())
                end
            end
        else
            ply:SetCycle((CurTime()-st)/num)

            local tab = AnimationTable[id].prop
            if CLIENT and istable(tab) and (!IsValid(ply.TauntProp) or ply.TauntProp:GetModel() != tab.model) then
                if IsValid(ply.TauntProp) then
                    ply.TauntProp:Remove()
                end
                ply.TauntProp = ClientsideModel(tab.model)
                tab.spawnfunc(ply.TauntProp, ply)
            elseif CLIENT and !istable(tab) and IsValid(ply.TauntProp) then
                ply.TauntProp:Remove()
            end
        end
        return -1, ply:LookupSequence(str)
    else
        if SERVER then
            ply:SetNWFloat('TauntID', 0)
        else
            if IsValid(ply.TauntProp) then
                ply.TauntProp:Remove()
            end
        end
    end
end)
