<#
.SYNOPSIS
    A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
    A longer description of the function, its purpose, common use cases, etc.
.NOTES
    Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
    Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
    Test-MyTestFunction -Verbose
    Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>

function New-ITDVMNetwork {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory = $true)]
        [string]
        $CIDR,

        [Parameter(Mandatory = $true)]
        [ValidateLength(3, 4)]
        [string]
        $VlanId,

        [Parameter(Mandatory = $true)]
        [ValidateSet("Data-Server", "Data-User")]
        [string]
        $DataType,

        #[PSCredential]
        #$SharePointCredential,

        [PSCredential]
        $vCenterCredential
    )
    
    begin {
        If ($VlanId -eq "MAC" -or $VlanId -eq "MAG") {
            $Hypervisor = "Azure"
        }
        Else {
            $Hypervisor = "VMware"
        }
        Write-Verbose "Hypervisor $Hypervisor"
        #VMware
        If ($Hypervisor -eq "VMware") {
            $ConnectITDvCenterParams = @{ }
            If ($vCenterCredential) { $ConnectITDvCenterParams += @{Credential = $vCenterCredential } }
            Connect-ITDvCenter @ConnectITDvCenterParams

            switch ($DataType) {
                'Data-Server' {
                    $BismarckVDSwitch = 'dvSwitch-PDC-Data-Server'
                    $MandanVDSwitch = 'dvSwitch-SDC-Data-Server'
                }
                'Data-User' {
                    $BismarckVDSwitch = 'dvSwitch-PDC-Data-User'
                    $MandanVDSwitch = 'dvSwitch-SDC-Data-User'
                }
            }
            

            $PortGroupList = Get-VirtualPortGroup
        }

        <#SharePoint
        $InvokeWebRequestParams = $null
        If ($SharePointCredential) { $InvokeWebRequestParams += @{Credential = $SharePointCredential } }
        Else { $InvokeWebRequestParams += @{UseDefaultCredentials = $true } }

        $UrlContextInfo = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/contextinfo"
        $InvokeWebRequestParams = @{
            Uri             = $UrlContextInfo;
            Method          = "Post";
            UseBasicParsing = $true;
        }
        If ($Credential) { $InvokeWebRequestParams += @{Credential = $Credential } }
        Else { $InvokeWebRequestParams += @{UseDefaultCredentials = $true } }
        #$RequestDigest = Invoke-RestMethod -Uri $UrlContextInfo -Method Post -UseDefaultCredentials
        $RequestDigest = Invoke-RestMethod @InvokeWebRequestParams
        $RequestDigest = $RequestDigest.GetContextWebInformation.FormDigestValue
        
        $UrlList = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/lists/getbytitle('VM Networks')"
        $InvokeWebRequestParams = @{
            Uri             = $UrlList;
            UseBasicParsing = $true;
        }
        If ($Credential) { $InvokeWebRequestParams += @{Credential = $Credential } }
        Else { $InvokeWebRequestParams += @{UseDefaultCredentials = $true } }
        #$List = Invoke-RestMethod -uri $UrlList -UseDefaultCredentials
        $List = Invoke-RestMethod @InvokeWebRequestParams
        $ListItemEntityTypeFullName = $list.entry.content.properties.ListItemEntityTypeFullName

        $UrlListItems = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/lists/getbytitle('VM Networks')/items" + '?$top=10000'

        $header = @{
            "accept"          = "application/json;odata=verbose"
            "X-RequestDigest" = $RequestDigest
        }
            #>
    }
    
    process {
        try {
            <#
            If ($SharePointCredential) { $GetITDVMwareSharePointNetworkListParams += @{Credential = $SharePointCredential } }
            $NetworkList = Get-ITDVMwareSharePointNetworkList @GetITDVMwareSharePointNetworkListParams
            #>
            $NetworkId = $CIDR.split('/')[0]
            $NetworkMask = $CIDR.split('/')[1]

            If ($VlanId -match "^\d+$" -and $VlanId.length -eq 3) {
                $VlanId = "0" + $VlanId
            }

            <# Verify CIDR not already in SharePoint
            If (@($NetworkList | Where-Object CIDR -EQ $CIDR)) {
                Write-Error "CIDR already exists in SharePoint"
            }
                #>

            # If VMware, do more checks then create port group
            If ($Hypervisor -eq "VMware") {
                # verify VlanId not already in sharepoint
                If (@($NetworkList | Where-Object Vlan_Id -EQ $VlanId)) {
                    Write-Error "Vlan Id already exists in SharePoint"
                    Exit
                }

                # verify Vlan Id not already in vmware portgroup
                If (@($PortGrouplist | Where-Object { $_.Name.split('_')[2] -eq $NetworkId })) {
                    Write-Error "Network_Id already exists in VMware PortGroup name"
                    Exit
                }
                If (@($PortGrouplist | Where-Object { $_.Name.split('_')[1] -eq $VlanId } )) {
                    Write-Error "VlanId already exists in VMware PortGroup name"
                    Exit
                }

                # Add new port group to VMware
                $PGName = "dvPG_" + $VlanId + "_" + $NetworkId + "_" + $NetworkMask
                
                Get-VDSwitch -Name $BismarckVDSwitch | New-VDPortgroup -Name $PGName -NumPorts 1 -VlanId $VlanId
                Get-VDSwitch -Name $BismarckVDSwitch | Get-VDPortgroup | Where-Object { $_.Name -like ("*_" + $VlanId + "_*") } | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -FailoverDetectionPolicy BeaconProbing
                Get-VDSwitch -Name $BismarckVDSwitch | Get-VDPortgroup | Where-Object { $_.Name -like ("*_" + $VlanId + "_*") } | Get-VDPortgroupOverridePolicy | Set-VDPortgroupOverridePolicy -BlockOverrideAllowed $false -ResetPortConfigAtDisconnect $false 
                Get-VDSwitch -Name $BismarckVDSwitch | Get-VDPortgroup | Where-Object { $_.Name -like ("*_" + $VlanId + "_*") } | Get-VDSecurityPolicy | Set-VDSecurityPolicy -MacChanges $false -AllowPromiscuous $false

                Get-VDSwitch -Name $MandanVDSwitch | New-VDPortgroup -Name $PGName -NumPorts 1 -VlanId $VlanId
                Get-VDSwitch -Name $MandanVDSwitch | Get-VDPortgroup | Where-Object { $_.Name -like ("*_" + $VlanId + "_*") } | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -FailoverDetectionPolicy BeaconProbing 
                Get-VDSwitch -Name $MandanVDSwitch | Get-VDPortgroup | Where-Object { $_.Name -like ("*_" + $VlanId + "_*") } | Get-VDPortgroupOverridePolicy | Set-VDPortgroupOverridePolicy -BlockOverrideAllowed $false -ResetPortConfigAtDisconnect $false
                Get-VDSwitch -Name $MandanVDSwitch | Get-VDPortgroup | Where-Object { $_.Name -like ("*_" + $VlanId + "_*") } | Get-VDSecurityPolicy | Set-VDSecurityPolicy -MacChanges $false -AllowPromiscuous $false
            }

            # Get PA7050 Zone info
            If ($Hypervisor -eq "Azure") { 
                $Secure = "True"
                $PA_Zone = "Azure"
                $AutoUpdate = $false

            }
            If ($Hypervisor -eq "VMware") {
                #$PAInterface = Get-ITDPAInterface -Number ($VlanId.TrimStart('0'))
                #If (@($PAInterface).count -gt 1) {
                #    Write-Error "More than one PA Interface found"
                #    exit
                #}
                #else {
                #    $Secure = [string]$PAInterface.ZeroTrust
                #    $PA_Zone = $PAInterface.Zone
                #    $AutoUpdate = $true
                #}
            }

            <# Add to SharePoint
            [PSCustomObject]$NewRecord = @{
                "__metadata" = @{type = $ListItemEntityTypeFullName } 
            }
            $NewRecord += @{Title = ("new_" + $env:USERNAME) }
            $NewRecord += @{CIDR = $CIDR }
            $NewRecord += @{DataType = $DataType }
            $NewRecord += @{Vlan_Id = $VlanId }
            $NewRecord += @{PA_Zone = $PA_Zone }
            $NewRecord += @{Secure = $Secure }
            $NewRecord += @{AutoUpdate = $AutoUpdate }
            $InvokeWebRequestParams = @{
                Uri             = $UrlListItems;
                Method          = "Post";
                Body            = $NewRecord | ConvertTo-Json;
                ContentType     = "application/json;odata=verbose";
                Headers         = $Header;
                UseBasicParsing = $AutoUpdate;
            }
            If ($SharePointCredential) { $InvokeWebRequestParams += @{Credential = $SharePointCredential } }
            Else { $InvokeWebRequestParams += @{UseDefaultCredentials = $true } }
            Invoke-RestMethod @InvokeWebRequestParams
            #>
        }
        catch {
            Write-Error $error[0] 
        }        
    }
    
    end {
        
    }
}