---------------------------------------------------------------------



local PlayerList = {}
PlayerList.__index = PlayerList


function PlayerList.new( holder ): ( {} )
    local self = setmetatable({}, PlayerList )
    self._janitor = Janitor.new()

    local function SortList()
        local killCounts = {}
        for index, icon in pairs( holder:GetChildren() ) do 
            local player = game.Players:FindFirstChild(icon.Name)
            if not player then continue end
            table.insert(killCounts, {
                player = player;
                kills = player:GetAttribute("Kills")
            })
        end
        table.sort(killCounts, function(a,b)
            return a.kills < b.kills 
        end)
        for index, killData in pairs( killCounts ) do 
            local playerIcon = holder[ killData.player.Name ]
            playerIcon.LayoutOrder = index
        end
    end

    local function OnPlayerAdded( player: Player ): ()
        local icon = PlayerIcon:Clone()
        local playerIcon: ImageLabel = icon:WaitForChild("Icon")
        icon.Name = player.Name
        playerIcon.Image = game.Players:GetUserThumbnailAsync(player.UserId, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size420x420)
        local points: TextLabel = icon:WaitForChild("Points")
        points.Text = player:GetAttribute("Kills") or 0
        icon.Parent = holder
        player:GetAttributeChangedSignal("Kills"):Connect(function()
            points.Text = player:GetAttribute("Kills")
            SortList()
        end)
		SortList()
		icon.BackgroundColor = player.Team.TeamColor
	end
	
	local function teamChange( )
		--if holder[game.Players.LocalPlayer.Name] then
		--	holder[game.Players.LocalPlayer.Name].BackgroundColor = game.Players.LocalPlayer.Team.TeamColor
		--end
	end

    local function OnPlayerRemoving( player: Player )
        local icon = holder[ player.Name ]
        icon:Destroy()
    end

    for index, player in pairs( game.Players:GetPlayers() ) do 
        OnPlayerAdded(player)
    end

    self._janitor:Add( game.Players.PlayerAdded:Connect(OnPlayerAdded) )
	self._janitor:Add( game.Players.PlayerRemoving:Connect(OnPlayerRemoving) )
	self._janitor:Add( game.Players.LocalPlayer:GetPropertyChangedSignal("TeamColor"):Connect(teamChange) )
    self._janitor:Add(function()
        for index, playerIcon in pairs( holder:GetChildren() ) do 
            if playerIcon:IsA("ImageButton") then 
                playerIcon:Destroy()
            end
        end
    end)

    local function OnScreenChanged( screenName: string ): () 
        holder.Visible = if screenName == "PlayerList" then true else false
    end
    
    return self
end


function PlayerList:Destroy(): ()
    self._janitor:Destroy()
end


return PlayerList
