Add-Type -assembly System.Windows.Forms

$main_form = New-Object System.Windows.Forms.Form

$main_form.Text = "ogibiotec - OGI 3 - BR4.6.0"
$main_form.Width = 600
$main_form.Height = 400

$Label = New-Object System.Windows.Forms.Label
$Label.Text = "Select COM port"
#
# Set font family name and size
$Label.Font = 'Courier New,14'

# Set element position based on pixels from left and top of form
$Label.Location = New-Object System.Drawing.Point(0,10)
$Label.AutoSize = $true
$main_form.Controls.Add($Label)

$ComboBox = New-Object System.Windows.Forms.ComboBox
$ComboBox.Width = 300
$ComboBox.Location = New-Object System.Drawing.Point(190,10)
$main_form.Controls.Add($ComboBox)

$ComboBox.Items.Clear()
$portobjs = Get-CimInstance Win32_SerialPort | Select-Object -Property Name # List Serial ports

Foreach ($portobj in $portobjs)
{
  $ComboBox.Items.Add($portobj.Name);
}

$RefreshButton = New-Object System.Windows.Forms.Button
$RefreshButton.Location = New-Object System.Drawing.Point(500,10)
$RefreshButton.Size = New-Object System.Drawing.Size(80,23)
$RefreshButton.Text = "Refresh"
$main_form.Controls.Add($RefreshButton)

$RefreshButton.Add_Click({
  $ComboBox.Items.Clear()
  $portobjs = Get-CimInstance Win32_SerialPort | Select-Object -Property Name # List Serial ports

  Foreach ($portobj in $portobjs)
  {
    $ComboBox.Items.Add($portobj.Name);
  }
})

$Output = New-Object System.Windows.Forms.TextBox
$Output.Font = 'Courier New,10'
$Output.Location = New-Object System.Drawing.Point(10,50)
$Output.Size = New-Object System.Drawing.Size(570,270)
$Output.multiline = $true
$Output.Scrollbars = "Vertical"
$Output.Anchor = "Top,Left,Bottom,Right"
if (![System.IO.File]::Exists("C:\Windows\System32\drivers\silabser.sys")) {
  $Output.Text = "WiFi Module Driver not installed! Please check README.txt for instructions.`n"
}
$main_form.Controls.Add($Output)

#############################################################################################
# Main board upload

$MainButton = New-Object System.Windows.Forms.Button
$MainButton.Location = New-Object System.Drawing.Point(10,330)
$MainButton.Size = New-Object System.Drawing.Size(140,23)
$MainButton.Text = "Upload BOARD PROG."
$MainButton.Anchor = 'Bottom,Left'
$main_form.Controls.Add($MainButton)

$MainButton.Add_Click(
  {
  $MainButton.Text = "Uploading"
  $Job = Start-ThreadJob {
    if (-not ($Using:ComboBox).selectedItem) {
      ($Using:Output).AppendText("No port selected `n")
      Return
    }

    $portfound = ($Using:ComboBox).selectedItem -match "COM[0-9]*"
    $portname = $Matches.Values

    $port = New-Object System.IO.Ports.SerialPort $portname,1200,None,8,one               # Establish connection
    try {
      $port.open()
      $port.close()
    }
    catch {
      ($Using:Output).AppendText("Failed!")
    }

    .\bin\bossac -i -d --port=$portname -U false -e -w -v -b .\bin\OGIBIOreactor.bin -R 2>&1 |
    Select-String -CaseSensitive "No device.*|Erase.*|done.*|Write.*|Verify.*|CPU.*|\[.+pages\)" |  # Print progress & useful info
    foreach {$_.Matches.Value | Out-String}
  }

  While ($Job.State -ne "Completed") {
    Start-Sleep -Seconds 1

    $txt = Receive-Job -Job $Job
    $Output.AppendText($txt)
  }
  $MainButton.Text = "Upload BOARD PROG."
  }
)

#############################################################################################
# WiFi board upload

$WiFiButton = New-Object System.Windows.Forms.Button
$WiFiButton.Location = New-Object System.Drawing.Point(160,330)
$WiFiButton.Size = New-Object System.Drawing.Size(140,23)
$WiFiButton.Text = "Upload WIFI PROG."
$WiFiButton.Anchor = 'Bottom,Left'
$main_form.Controls.Add($WiFiButton)

$WiFiButton.Add_Click(
  {
  $WiFiButton.Text = "Uploading"
  $Job = Start-ThreadJob {
    if (-not ($Using:ComboBox).selectedItem) {
      ($Using:Output).AppendText("No port selected `n")
      Return
    }

    $portfound = ($Using:ComboBox).selectedItem -match "COM[0-9]*"
    $portname = $Matches.Values

    $port = New-Object System.IO.Ports.SerialPort $portname,1200,None,8,one               # Establish connection
    try {
      $port.open()
      $port.close()
    }
    catch {
      ($Using:Output).AppendText("Failed!")
    }

    .\bin\esptool --chip esp32s3 --port $portname --baud 921600  --before default_reset --after hard_reset write_flash  -z --flash_mode dio --flash_freq 80m --flash_size 8MB 0x0000 .\bin\bootloader.bin 0x8000 .\bin\partitions.bin 0xe000 .\bin\boot_app0.bin 0x10000 .\bin\WiFiModule.bin 2>&1 |
    Select-String -CaseSensitive "A fatal.*|Connecting.*|Flash.*|Writing.*|Wrote.*|Hash.*|Hard.*" |  # Print progress & useful info
    foreach {$_.Matches.Value | Out-String}

  }

  While ($Job.State -ne "Completed") {
    Start-Sleep -Seconds 0.2

    $txt = Receive-Job -Job $Job
    $Output.AppendText($txt)
  }
  $WiFiButton.Text = "Upload WIFI PROG."
  }
)

#############################################################################################
# Help

$HelpButton = New-Object System.Windows.Forms.Button
$HelpButton.Location = New-Object System.Drawing.Point(310,330)
$HelpButton.Size = New-Object System.Drawing.Size(140,23)
$HelpButton.Text = "Help"
$HelpButton.Anchor = "Bottom,Left"
$main_form.Controls.Add($HelpButton)

$PortPicture = New-Object Windows.Forms.PictureBox
$file = Get-Item "./bin/ports_squared.png"
$img = [System.Drawing.Image]::FromFile((Get-Item $file))
$PortPicture.Image = $img
$PortPicture.Location = New-Object System.Drawing.Point(75,10)
$PortPicture.AutoSize = $true
$PortPicture.Hide()
$main_form.Controls.Add($PortPicture)

$HelpLabel = New-Object System.Windows.Forms.Label
$HelpLabel.Text =
@"
  1. Connect your PC to the `"BOARD PROG.`" port on the rear of the device
  2. Select the correct port from the dropdown menu
  3. You can Refresh the list of devices with the `"Refresh`" button
  4. Use the `"Upload BOARD PROG.`" button to update the main board
  5. The last message displayed after a successful upload will be `"CPU reset`"
  6. When complete, connect your PC to the `"WIFI PROG.`" port on the rear of the device
  7. Refresh the list of ports and select the new port
  8. Use the `"Upload WIFI PROG.`" button to update the wifi board
  9. The last message displayed after a successful upload will be `"Hard resetting via RTS pin...`"
"@
$HelpLabel.Location = New-Object System.Drawing.Point(10,150)
$HelpLabel.AutoSize = $true
$HelpLabel.Hide()
$main_form.Controls.Add($HelpLabel)


$HelpVisibility = $false

$HelpButton.Add_Click({
  if (!$HelpVisibility) {
    # Hide updater elements
    $Label.Hide()
    $ComboBox.Hide()
    $RefreshButton.Hide()
    $Output.Hide()
    $MainButton.Hide()
    $WiFiButton.Hide()
    $HelpButton.Text = "Close"
    ($global:HelpVisibility) = $true

    # Show help elements
    $PortPicture.Show()
    $HelpLabel.Show()
  } else {
    # Show updater elements
    $Label.Show()
    $ComboBox.Show()
    $RefreshButton.Show()
    $Output.Show()
    $MainButton.Show()
    $WiFiButton.Show()
    $HelpButton.Text = "Help"
    ($global:HelpVisibility) = $false

    # Hide help elements
    $PortPicture.Hide()
    $HelpLabel.Hide()
  }
})



#############################################################################################
# Display - THIS MUST COME LAST
$main_form.ShowDialog()

