PLUGIN.name = "Меню выдачи предметов (SuperAdmin)"
PLUGIN.author = "RefoselTeamWork"
PLUGIN.description = "Adds a tab to the spawn menu which players can use to spawn items."

CAMI.RegisterPrivilege({
    Name = "Helix - Выдача предметов",
    MinAccess = "superadmin"
})

function PLUGIN:GetExpectedIcon(s)
    local i = {
        ["Патроны"] = "icon16/tab.png"
    }

    return hook.Run("GetIconsForSpawnMenuItems", s) or i[s] or "icon16/folder.png"
end

if SERVER then
    util.AddNetworkString("spawnmenuspawnitem")
    util.AddNetworkString("spawnmenugiveitem")
    ix.log.AddType("spawnmenuspawnitem", function(client, name) return string.format("%s has spawned \"%s\".", client:GetCharacter():GetName(), tostring(name)) end)

    net.Receive("spawnmenuspawnitem", function(len, client)
        local u = net.ReadString()
        if not CAMI.PlayerHasAccess(client, "Helix - Выдача предметов", nil) then return end

        for _, t in pairs(ix.item.list) do
            if t.uniqueID == u then
                ix.item.Spawn(t.uniqueID, client:GetShootPos() + client:GetAimVector() * 84 + Vector(0, 0, 16))
                ix.log.Add(client, "spawnmenuspawnitem", t.name)
                break
            end
        end
    end)

    net.Receive("spawnmenugiveitem", function(len, client)
        local u = net.ReadString()
        if not CAMI.PlayerHasAccess(client, "Helix - Выдача предметов", nil) then return end

        for _, t in pairs(ix.item.list) do
            if t.uniqueID == u then
                local character = client:GetCharacter()
                if not character then return end

                local inventory = character:GetInventory()
                if not inventory or isnumber(inventory) then
                    client:Notify("Inventory is still loading, please wait...")
                    return
                end

                inventory:Add(t.uniqueID)
                ix.log.Add(client, "spawnmenuspawnitem", t.name)
                client:Notify("You have given yourself a " .. t.name .. ". Check your inventory.")
                break
            end
        end
    end)
else
    function PLUGIN:InitializedPlugins()
        if SERVER then return end
        RunConsoleCommand("spawnmenu_reload")
    end

    local PLUGIN = PLUGIN

    spawnmenu.AddCreationTab("SuperAdmin - Выдача", function()
        local p = vgui.Create("SpawnmenuContentPanel")
        local t, n = p.ContentNavBar.Tree, p.OldSpawnlists
        local l = {}

        for uid, i in pairs(ix.item.list) do
            local c = i.category
            l[c] = l[c] or {}
            table.insert(l[c], i)
        end

        for c, i in SortedPairs(l) do
            local icon16 = PLUGIN:GetExpectedIcon(c)
            local node = t:AddNode(L(c), icon16)

            node.DoClick = function(self)
                if self.PropPanel and IsValid(self.PropPanel) then
                    self.PropPanel:Remove()
                    self.PropPanel = nil
                end

                self.PropPanel = vgui.Create("ContentContainer", p)
                self.PropPanel:SetVisible(false)
                self.PropPanel:SetTriggerSpawnlistChange(false)

                for _, t in SortedPairsByMemberValue(i, "name") do
                    spawnmenu.CreateContentIcon("item", self.PropPanel, {
                        nicename = (t.GetName and t:GetName()) or t.name,
                        spawnname = t.uniqueID,
                    })
                end

                p:SwitchPanel(self.PropPanel)
            end
        end

        local FirstNode = t:Root():GetChildNode(0)

        if IsValid(FirstNode) then
            FirstNode:InternalDoClick()
        end

        return p
    end, "icon16/cog_add.png", 201)

    spawnmenu.AddContentType("item", function(p, data)
        local n = data.nicename
        local u = data.spawnname
        local icon = vgui.Create("SpawnIcon", p)
        icon:SetWide(64)
        icon:SetTall(64)
        icon:InvalidateLayout(true)
        local t = ix.item.list
        local i = t[u]
        icon:SetModel((i.GetModel and i:GetModel()) or i.model)
        icon:SetTooltip(n)

        icon.OnMousePressed = function(this, code)
            surface.PlaySound("ui/buttonclickrelease.wav")
            if not CAMI.PlayerHasAccess(LocalPlayer(), "Helix - Выдача предметов", nil) then return end

            if code == MOUSE_LEFT then
                net.Start("spawnmenuspawnitem")
                net.WriteString(u)
                net.SendToServer()
            elseif code == MOUSE_RIGHT then
                net.Start("spawnmenugiveitem")
                net.WriteString(u)
                net.SendToServer()
            end
        end

        icon:InvalidateLayout(true)

        if IsValid(p) then
            p:Add(icon)
        end

        return icon
    end)
end
