PSFPL.psm1

Write-Verbose 'Importing from [D:\a\1\s\PSFPL\Private]'
# .ConvertTo-FplObject.ps1
function ConvertTo-FplObject {
    <#
    .SYNOPSIS
        Convert an object returned from the FPL API into a more PowerShelly object with a type name
    .DESCRIPTION
        Convert an object returned from the FPL API into a more PowerShelly object with a type name
    .PARAMETER InputObject
        A PowerShell object returned from the FPL API
    .PARAMETER Type
        The type name to give the resulted PowerShell object
    .EXAMPLE
        $Response = Invoke-RestMethod -Uri 'https://fantasy.premierleague.com/drf/elements/' -UseBasicParsing
        ConvertTo-FplObject -InputObject $Response -Type 'FplPlayer'
    .LINK
        https://github.com/sk82jack/PSFPL/
    #>

    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)]
        [object[]]
        $InputObject,

        [Parameter(Mandatory)]
        [ValidateSet('FplPlayer', 'FplGameweek', 'FplFixture', 'FplLeagueTable', 'FplTeam', 'FplLeague', 'FplTeamPlayer')]
        [string]
        $Type
    )
    switch ($Type) {
        'FplPlayer' {
            $PositionHash = Get-FplElementType
            $TeamHash = Get-FplClubId
        }
        'FplFixture' {
            $TeamHash = Get-FplClubId
            $PlayerHash = Get-FplElementId
        }
        'FplLeagueTable' {
            $LeagueName = $InputObject[0].league.name
            $InputObject = $InputObject.foreach{$_.standings.results}
        }
        'FplTeam' {
            $TeamHash = Get-FplClubId
        }
        'FplLeague' {
            $InputObject = @($InputObject.classic) + @($InputObject.h2h).where{$_.name -ne 'cup'}
        }
        'FplTeamPlayer' {
            $Players = Get-FplPlayer
        }
    }

    $TextInfo = (Get-Culture).TextInfo
    foreach ($Object in $InputObject) {
        $Hashtable = [ordered]@{}
        $Object.psobject.properties | Foreach-Object {
            $Name = $TextInfo.ToTitleCase($_.Name) -replace '_' -replace 'Team', 'Club' -replace 'Entry', 'Team' -replace 'Event', 'Gameweek'
            $Value = if ($_.Value -is [string]) {
                $DiacriticName = [Text.Encoding]::UTF8.GetString([Text.Encoding]::GetEncoding('ISO-8859-1').GetBytes($_.Value))
                [Text.Encoding]::ASCII.GetString([Text.Encoding]::GetEncoding("Cyrillic").GetBytes($DiacriticName)).trim()
            }
            else {
                $_.Value
            }
            $Hashtable[$Name] = $Value
        }

        switch ($Type) {
            'FplPlayer' {
                $Hashtable['PlayerId'] = $Hashtable['Id']
                $Hashtable.Remove('Id')
                $Hashtable['Position'] = $PositionHash[$Object.element_type]
                $Hashtable['ClubId'] = $Hashtable['Club']
                $Hashtable['Club'] = $TeamHash[$Hashtable['Club']]
                $Hashtable['Price'] = $Object.now_cost / 10
            }
            'FplGameweek' {
                $Hashtable['Gameweek'] = $Hashtable['Id']
                $Hashtable.Remove('Id')
                $Hashtable['DeadlineTime'] = Get-Date $Object.deadline_time
            }
            'FplFixture' {
                $Hashtable['FixtureId'] = $Hashtable['Id']
                $Hashtable.Remove('Id')
                $Hashtable['DeadlineTime'] = Get-Date $Object.deadline_time
                $HashTable['KickoffTime'] = Get-Date $Object.kickoff_time
                $Hashtable['ClubA'] = $TeamHash[$Object.team_a]
                $Hashtable['ClubH'] = $TeamHash[$Object.team_h]
                $Hashtable['Stats'] = foreach ($Stat in $Hashtable['Stats']) {
                    $StatType = $TextInfo.ToTitleCase($Stat.PSObject.Properties.Name)
                    foreach ($Letter in 'a', 'h') {
                        $Club = 'Club{0}' -f $Letter.ToUpper()
                        foreach ($Item in $Stat.$StatType.$Letter) {
                            [pscustomobject]@{
                                'PlayerId'   = $Item.element
                                'PlayerName' = $PlayerHash[$Item.element]
                                'StatType'   = $StatType -replace '_'
                                'StatValue'  = $Item.value
                                'ClubName'   = $Hashtable[$club]
                            }
                        }
                    }
                }
            }
            'FplLeagueTable' {
                $Hashtable['LeagueName'] = $LeagueName
                $Hashtable['LeagueId'] = $Hashtable['League']
                $Hashtable.Remove('League')
                $Hashtable['TeamId'] = $Hashtable['Team']
                $Hashtable.Remove('Team')
            }
            'FplTeam' {
                $Hashtable['Bank'] = $Hashtable['Bank'] / 10
                $Hashtable['Value'] = $Hashtable['Value'] / 10
                if ($Hashtable['FavouriteClub']) {
                    $Hashtable['FavouriteClub'] = $TeamHash[$Hashtable['FavouriteClub']]
                }
                $Hashtable['TeamId'] = $Hashtable['Id']
                $Hashtable.Remove('Id')
                $Hashtable['PlayerId'] = $Hashtable['Player']
                $Hashtable.Remove('Player')
            }
            'FplLeague' {
                $Hashtable['LeagueId'] = $Hashtable['Id']
                $Hashtable.Remove('Id')
                $Hashtable['LeagueType'] = switch ($Hashtable['LeagueType']) {
                    'c' {'Public'}
                    's' {'Global'}
                    'x' {'Private'}
                }
                $Hashtable['Scoring'] = switch ($Hashtable['Scoring']) {
                    'c' {'Classic'}
                    'h' {'H2H'}
                }
            }
            'FplTeamPlayer' {
                $Hashtable['PlayerId'] = $Hashtable['Element']
                $Hashtable.Remove('Element')
                if ($Hashtable.position -le 11) {
                    $Hashtable['PlayingStatus'] = 'Starting'
                }
                else {
                    $Hashtable['PlayingStatus'] = 'Substitute'
                }

                $CurrentPlayer = $Players.Where{$_.PlayerId -eq $Hashtable['PlayerId']}
                foreach ($Property in (Get-Member -InputObject $CurrentPlayer[0] -MemberType 'NoteProperty').Name) {
                    $Hashtable[$Property] = $CurrentPlayer.$Property
                }
                $Hashtable['Points'] = $CurrentPlayer.GameweekPoints * $Hashtable['Multiplier']
                $Hashtable.Remove('Multiplier')

            }
        }
        $Hashtable['PsTypeName'] = $Type
        [pscustomobject]$Hashtable
    }
}

# .Get-FplClubId.ps1
function Get-FplClubId {
    <#
    .SYNOPSIS
        Retrieves a hashtable of club IDs to club names
    .DESCRIPTION
        Retrieves a hashtable of club IDs to club names
    .EXAMPLE
        Get-FplClubId
    .LINK
        https://github.com/sk82jack/PSFPL/
    #>

    [CmdletBinding()]
    param ()
    $Response = Invoke-RestMethod -Uri 'https://fantasy.premierleague.com/drf/teams' -UseBasicParsing
    $Hashtable = @{}
    foreach ($Club in $Response) {
        $Hashtable[$Club.id] = $Club.name
    }
    $Hashtable
}

# .Get-FplElementId.ps1
function Get-FplElementId {
    <#
    .SYNOPSIS
        Retrieves a hashtable of player IDs to player names
    .DESCRIPTION
        Retrieves a hashtable of player IDs to player names
    .EXAMPLE
        Get-FplElementId
    .LINK
        https://github.com/sk82jack/PSFPL/
    #>

    [CmdletBinding()]
    param ()
    $Response = Invoke-RestMethod -Uri 'https://fantasy.premierleague.com/drf/elements/' -UseBasicParsing
    $Hashtable = @{}
    foreach ($Element in $Response) {
        $DiacriticName = [Text.Encoding]::UTF8.GetString([Text.Encoding]::GetEncoding('ISO-8859-1').GetBytes($Element.web_name))
        $Hashtable[$Element.id] = [Text.Encoding]::ASCII.GetString([Text.Encoding]::GetEncoding("Cyrillic").GetBytes($DiacriticName))
    }
    $Hashtable
}

# .Get-FplElementType.ps1
function Get-FplElementType {
    <#
    .SYNOPSIS
        Retrieves a hashtable of position IDs to position names
    .DESCRIPTION
        Retrieves a hashtable of position IDs to position names
    .EXAMPLE
        Get-FplElementType
    .LINK
        https://github.com/sk82jack/PSFPL/
    #>

    [CmdletBinding()]
    param ()
    $Response = Invoke-RestMethod -Uri 'https://fantasy.premierleague.com/drf/element-types' -UseBasicParsing
    $ElementHash = @{}
    foreach ($Element in $Response) {
        $ElementHash[$Element.id] = $Element.singular_name
    }
    $ElementHash
}

# .Get-FplUserTeam.ps1
function Get-FplUserTeam {
    <#
    .SYNOPSIS
        Retrieves the logged in users team
    .DESCRIPTION
        Retrieves the logged in users team
    .EXAMPLE
        Get-FplUserTeam
    .LINK
        https://github.com/sk82jack/PSFPL/
    #>

    [CmdletBinding()]
    param ()
    $Response = Invoke-RestMethod -Uri 'https://fantasy.premierleague.com/drf/transfers' -UseDefaultCredentials -WebSession $Script:FplSession
    ConvertTo-FplObject -InputObject $Response.entry -Type 'FplTeam'
}

Write-Verbose 'Importing from [D:\a\1\s\PSFPL\Public]'
# .Connect-FPL.ps1
function Connect-Fpl {
    <#
    .SYNOPSIS
        Connect to the FPL API using provided login credentials
    .DESCRIPTION
        Connect to the FPL API using provided login credentials
        This is required for some functions which pull data related to your account
    .PARAMETER Credential
        Your FPL credentials that you use to log into https://fantasy.premierleague.com
    .PARAMETER Force
        Create a connection regardless of whether there is already an existing connection
    .EXAMPLE
        Connect-FPL -Credential myname@email.com
    .EXAMPLE
        Connect-FPL -Credential myname@email.com -Force
    .LINK
        https://psfpl.readthedocs.io/en/latest/functions/Connect-Fpl
    .LINK
        https://github.com/sk82jack/PSFPL/blob/master/PSFPL/Public/Connect-FPL.ps1
    #>

    [Cmdletbinding()]
    Param (
        [Parameter(Mandatory)]
        [pscredential]
        $Credential,

        [Parameter()]
        [switch]
        $Force
    )

    if ($Script:FplSession -and -not $Force) {
        Write-Warning "A connection already exists. Use the Force parameter to connect."
        return
    }

    $Uri = 'https://users.premierleague.com/accounts/login/'
    $LoginResponse = Invoke-WebRequest -Uri $Uri -SessionVariable 'FplSession' -UseBasicParsing
    $CsrfToken = $LoginResponse.InputFields.Where{$_.name -eq 'csrfmiddlewaretoken'}.value

    $Response = Invoke-WebRequest -Uri $Uri -WebSession $FplSession -Method 'Post' -UseBasicParsing -Body @{
        'csrfmiddlewaretoken' = $CsrfToken
        'login'               = $Credential.UserName
        'password'            = $Credential.GetNetworkCredential().Password
        'app'                 = 'plfpl-web'
        'redirect_uri'        = 'https://fantasy.premierleague.com/a/login'
    }

    if (-not ($Response.Headers.'Set-Cookie' -match 'sessionid=')) {
        Throw 'Invalid credentials'
    }

    $Script:FplSession = $FplSession
}

# .Get-FplFixture.ps1
function Get-FplFixture {
    <#
    .SYNOPSIS
        Retrieves a list of FPL fixtures
    .DESCRIPTION
        Retrieves a list of FPL fixtures
    .PARAMETER Gameweek
        Retrieve the fixtures from a specified gameweek
    .PARAMETER Club
        Retrieve the fixtures for a specified club
    .EXAMPLE
        Get-FplFixture
 
        This will list all of the fixtures throughout the season
    .EXAMPLE
        Get-FplFixture -Gameweek 14
 
        This will list the fixtures from gameweek 14
    .EXAMPLE
        Get-FplFixture -Club Liverpool
 
        This will list all of the fixtures for Liverpool FC
    .EXAMPLE
        Get-FplFixture -Club Chelsea -Gameweek 2
 
        This will get the Chelsea FC fixture in gameweek 2
    .LINK
        https://psfpl.readthedocs.io/en/latest/functions/Get-FplFixture
    .LINK
        https://github.com/sk82jack/PSFPL/blob/master/PSFPL/Public/Get-FplFixture.ps1
    #>

    [CmdletBinding()]
    Param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [int]
        $Gameweek,

        [Parameter()]
        [ValidateSet(
            'Arsenal', 'Bournemouth', 'Brighton', 'Burnley', 'Cardiff', 'Chelsea', 'Crystal Palace',
            'Everton', 'Fulham', 'Huddersfield', 'Leicester', 'Liverpool', 'Man City', 'Man Utd',
            'Newcastle', 'Southampton', 'Spurs', 'Watford', 'West Ham', 'Wolves'
        )]
        [string]
        $Club
    )

    process {
        $Response = Invoke-RestMethod -Uri 'https://fantasy.premierleague.com/drf/fixtures/' -UseBasicParsing
        if ($Response -match 'The game is being updated.') {
            Write-Warning 'The game is being updated. Please try again shortly.'
            return
        }
        $Fixtures = ConvertTo-FplObject -InputObject $Response -Type 'FplFixture' | Sort-Object Gameweek, KickOffTime
        $Fixtures.Where{
            ($Gameweek -eq 0 -or $_.Gameweek -eq $Gameweek) -and
            $_.ClubH + $_.ClubA -match $Club
        }
    }
}

# .Get-FplGameweek.ps1
function Get-FplGameweek {
    <#
    .SYNOPSIS
        Retrieves a list of FPL gameweeks
    .DESCRIPTION
        Retrieves a list of FPL gameweeks
    .PARAMETER Gameweek
        Retrieve a specific gameweek by it's number
    .Parameter Current
        Retrieves the current gameweek
    .EXAMPLE
        Get-FplGameweek
 
        This will list all of the gameweeks
    .EXAMPLE
        Get-FplGameweek -Gameweek 14
 
        This will list only gameweek 14
    .EXAMPLE
        9 | Get-FplGameweek
 
        This will list only gameweek 9
    .EXAMPLE
        Get-FplGameweek -Current
 
        This will list only the current gameweek
    .LINK
        https://psfpl.readthedocs.io/en/latest/functions/Get-FplGameweek
    .LINK
        https://github.com/sk82jack/PSFPL/blob/master/PSFPL/Public/Get-FplGameweek.ps1
    #>

    [CmdletBinding(DefaultParameterSetName = 'Gameweek')]
    param (
        [Parameter(
            ParameterSetName = 'Gameweek',
            ValueFromPipeline
        )]
        [int]
        $Gameweek,

        [Parameter(ParameterSetName = 'Current')]
        [switch]
        $Current
    )

    $Response = Invoke-RestMethod -Uri 'https://fantasy.premierleague.com/drf/events/' -UseBasicParsing
    if ($Response -match 'The game is being updated.') {
        Write-Warning 'The game is being updated. Please try again shortly.'
        return
    }
    $Gameweeks = ConvertTo-FplObject -InputObject $Response -Type 'FplGameweek'

    if ($Current) {
        $Gameweeks.Where{$_.IsCurrent}
    }
    elseif ($Gameweek -gt 0) {
        $Gameweeks.Where{$_.Id -eq $Gameweek}
    }
    else {
        $Gameweeks
    }
}

# .Get-FplLeague.ps1
function Get-FplLeague {
    <#
    .SYNOPSIS
        Lists the leagues that a team is a member of.
    .DESCRIPTION
        Lists the leagues that a team is a member of given a team ID.
        If no team ID is specified then it will list the leagues for your team. This requires an existing connection which can be created with Connect-Fpl.
        If there is no existing connection found it will prompt for credentials.
    .PARAMETER TeamId
        The team ID of the team to list the leagues of.
    .EXAMPLE
        Get-FplLeague
 
        This will list the leagues that your team is in.
    .EXAMPLE
        Get-FplLeague -TeamId 12345
 
        This will list the leagues that the team with the team ID of 12345 is in.
    .LINK
        https://psfpl.readthedocs.io/en/latest/functions/Get-FplLeague
    .LINK
        https://github.com/sk82jack/PSFPL/blob/master/PSFPL/Public/Get-FplLeague.ps1
    #>


    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [int]
        $TeamId
    )

    process {
        if ($TeamId -eq 0) {
            if (!$Script:FplSession) {
                Write-Warning 'No existing connection found'
                $Credential = Get-Credential -Message 'Please enter your FPL login details'
                Connect-Fpl -Credential $Credential
            }

            $TeamId = (Get-FplUserTeam).TeamId
        }

        $Response = Invoke-RestMethod -Uri "https://fantasy.premierleague.com/drf/entry/$TeamId" -UseDefaultCredentials
        if ($Response -match 'The game is being updated.') {
            Write-Warning 'The game is being updated. Please try again shortly.'
            return
        }
        ConvertTo-FplObject -InputObject $Response.leagues -Type 'FplLeague'
    }
}

# .Get-FplLeagueTable.ps1
function Get-FplLeagueTable {
    <#
    .SYNOPSIS
        Retrieves an FPL league table
    .DESCRIPTION
        Retrieves an FPL league table given a league ID and league type
    .PARAMETER LeagueId
        An FPL league Id
    .Parameter Type
        An FPL league type. This can either be 'Classic' or 'HeadToHead'
    .Parameter League
        This parameter allows you to pass in an FplLeague object directly which can be retrieved from Get-FplLeague
    .EXAMPLE
        Get-FplLeagueTable -Id 12345 -Type Classic
 
        This will show the league standings for the classic league of ID 12345
    .EXAMPLE
        Get-FplLeague | Where Name -eq 'My League' | Get-FplLeagueTable
 
        This will get the league standings for the league that your team is in called 'My League'
    .LINK
        https://psfpl.readthedocs.io/en/latest/functions/Get-FplLeagueTable
    .LINK
        https://github.com/sk82jack/PSFPL/blob/master/PSFPL/Public/Get-FplLeagueTable.ps1
    #>

    [CmdletBinding(DefaultParameterSetName = 'Default')]
    param (
        [Parameter(
            Mandatory,
            ParameterSetName = 'Default'
        )]
        [int]
        $LeagueId,

        [Parameter(
            Mandatory,
            ParameterSetName = 'Default'
        )]
        [ValidateSet('Classic', 'H2H')]
        [string]
        $Type,

        [Parameter(
            Mandatory,
            ValueFromPipeline,
            ParameterSetName = 'PipelineInput'
        )]
        [PSTypeName('FplLeague')]
        $League
    )

    process {
        if ($PSCmdlet.ParameterSetName -eq 'PipelineInput') {
            $Type = $League.Scoring
            $Id = $League.LeagueId
        }
        $Results = do {
            $Page += 1
            $Url = 'https://fantasy.premierleague.com/drf/leagues-{0}-standings/{1}?phase=1&le-page=1&ls-page={2}' -f $Type.ToLower(), $Id, $Page
            $Response = Invoke-RestMethod -Uri $Url -UseBasicParsing
            if ($Response -match 'The game is being updated.') {
                Write-Warning 'The game is being updated. Please try again shortly.'
                return
            }
            $Response
        }
        until (-not $Response.standings.has_next)

        ConvertTo-FplObject -InputObject $Results -Type 'FplLeagueTable'
    }
}

# .Get-FplPlayer.ps1
function Get-FplPlayer {
    <#
    .SYNOPSIS
        Retrieve a list of FPL players
    .DESCRIPTION
        Retrieve a list of FPL players
    .PARAMETER Name
        Filter players based on their surname
    .PARAMETER Position
        Filter players based on their position
    .PARAMETER Club
        Filter players based on their club
    .PARAMETER MaxPrice
        Filter players based on their price
    .PARAMETER DreamTeam
        Show the current dream team
    .EXAMPLE
        Get-FplPlayer
 
        Retrieve all of the FPL players in the game
    .EXAMPLE
        Get-FplPlayer -Name Hazard
 
        Retrieve all of the FPL players with 'Hazard' in their name
    .EXAMPLE
        Get-FplPlayer -Position Forward -Club 'Man City'
 
        Retrieve all of the forwards that play for Man City
    .EXAMPLE
        Get-FplPlayer -MaxPrice 5.1
 
        Retrieve all players priced at �5.1m or lower
    .EXAMPLE
        Get-FplPlayer -DreamTeam
 
        Retrieve the current dream team
    .LINK
        https://psfpl.readthedocs.io/en/latest/functions/Get-FplPlayer
    .LINK
        https://github.com/sk82jack/PSFPL/blob/master/PSFPL/Public/Get-FplPlayer.ps1
    #>

    [CmdletBinding(DefaultParameterSetName = 'Filter')]
    Param (
        [Parameter(
            ParameterSetName = 'Filter',
            ValueFromPipeline
        )]
        [string]
        $Name,

        [Parameter(ParameterSetName = 'Filter')]
        [ValidateSet('Forward', 'Midfielder', 'Defender', 'Goalkeeper')]
        [string]
        $Position,

        [Parameter(ParameterSetName = 'Filter')]
        [ValidateSet(
            'Arsenal', 'Bournemouth', 'Brighton', 'Burnley', 'Cardiff', 'Chelsea', 'Crystal Palace',
            'Everton', 'Fulham', 'Huddersfield', 'Leicester', 'Liverpool', 'Man City', 'Man Utd',
            'Newcastle', 'Southampton', 'Spurs', 'Watford', 'West Ham', 'Wolves'
        )]
        [string]
        $Club,

        [Parameter(ParameterSetName = 'Filter')]
        [double]
        $MaxPrice = [int]::MaxValue,

        [Parameter(ParameterSetName = 'DreamTeam')]
        [switch]
        $DreamTeam
    )
    Begin {
        $Response = Invoke-RestMethod -Uri 'https://fantasy.premierleague.com/drf/elements/' -UseBasicParsing
        if ($Response -match 'The game is being updated.') {
            Write-Warning 'The game is being updated. Please try again shortly.'
            return
        }
        $Players = ConvertTo-FplObject -InputObject $Response -Type 'FplPlayer' | Sort-Object TotalPoints, Price -Descending
    }
    Process {
        $Output = $Players.Where{
            $_.WebName -match $Name -and
            $_.Position -match $Position -and
            $_.Club -match $Club -and
            $_.Price -le $MaxPrice
        }
        if ($PSBoundParameters.ContainsKey('MaxPrice')) {
            $Output = $Output | Sort-Object Price, TotalPoints -Descending
        }
        if ($DreamTeam) {
            $SortOrder = 'Goalkeeper', 'Defender', 'Midfielder', 'Forward'
            $Output = $Players.Where{$_.InDreamClub -eq $true} | Sort-Object {$SortOrder.IndexOf($_.Position)}
        }
        $Output
    }
    End {}
}

# .Get-FplTeam.ps1
function Get-FplTeam {
    <#
    .SYNOPSIS
        Retrieve information about an FPL team
    .DESCRIPTION
        Retrieve information about an FPL team either by a specified team ID or get your own team by logging in with Connect-FPL
    .PARAMETER TeamId
        A team ID to retrieve information about
    .EXAMPLE
        Connect-Fpl -Email MyEmail@hotmail.com
        $MyTeam = Get-FplTeam
 
        Retrieves information about your own team
    .EXAMPLE
        Get-FplTeam -TeamId 12345
 
        Retrieves information about the team with the ID 12345
    .LINK
        https://psfpl.readthedocs.io/en/latest/functions/Get-FplTeam
    .LINK
        https://github.com/sk82jack/PSFPL/blob/master/PSFPL/Public/Get-FplTeam.ps1
    #>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [int]
        $TeamId
    )
    process {
        if ($TeamId -gt 0) {
            $Response = Invoke-RestMethod -Uri "https://fantasy.premierleague.com/drf/entry/$TeamId" -UseDefaultCredentials
            if ($Response -match 'The game is being updated.') {
                Write-Warning 'The game is being updated. Please try again shortly.'
                return
            }
            ConvertTo-FplObject -InputObject $Response.entry -Type 'FplTeam'
        }
        else {
            if (!$Script:FplSession) {
                Write-Warning 'No existing connection found'
                $Credential = Get-Credential -Message 'Please enter your FPL login details'
                Connect-Fpl -Credential $Credential
            }

            Get-FplUserTeam
        }
    }
}

# .Get-FplTeamPlayer.ps1
function Get-FplTeamPlayer {
    <#
    .SYNOPSIS
        Retrieves the player information within a team from a certain gameweek.
    .DESCRIPTION
        Retrieves the player information within a team from a certain gameweek.
        If no team ID or gameweek is supplied it will request to authenticate to get the users team and current gameweek.
    .PARAMETER TeamId
        The ID of the team to retrieve the player information
    .PARAMETER Gameweek
        The gameweek of which to retrieve the player information from
    .EXAMPLE
        Get-FplTeamPlayer
 
        This will prompt the user to supply credentials and return the user's player information from the current gameweek
    .EXAMPLE
        Get-FplTeamPlayer -TeamID 12345
 
        This will get the player information for the team with ID 12345 from the current gameweek
    .EXAMPLE
        Get-FplTeamPlayer -TeamID 12345 -Gameweek 12
 
        This will get the player information for the team with ID 12345 from gameweek 12
    .LINK
        https://psfpl.readthedocs.io/en/latest/functions/Get-FplTeamPlayer
    .LINK
        https://github.com/sk82jack/PSFPL/blob/master/PSFPL/Public/Get-FplTeamPlayer.ps1
    #>


    [CmdletBinding()]
    param (
        [Parameter()]
        [int]
        $TeamId,

        [Parameter()]
        [int]
        $Gameweek
    )
    process {
        if ($TeamId -eq 0) {
            if (!$Script:FplSession) {
                Write-Warning 'No existing connection found'
                $Credential = Get-Credential -Message 'Please enter your FPL login details'
                Connect-Fpl -Credential $Credential
            }

            $TeamId = (Get-FplUserTeam).TeamId
        }

        if ($Gameweek -eq 0) {
            $Gameweek = (Get-FplGameweek -Current).Gameweek
        }

        $Response = Invoke-RestMethod -Uri "https://fantasy.premierleague.com/drf/entry/$TeamId/event/$Gameweek/picks"
        if ($Response -match 'The game is being updated.') {
            Write-Warning 'The game is being updated. Please try again shortly.'
            return
        }
        ConvertTo-FplObject -InputObject $Response.picks -Type 'FplTeamPlayer'
    }
}