Imports EgtUILib

Public Class MachineCNPageUC

   ' Riferimento alla MainWindow
   Private m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
   Friend m_CN As CN_generico
   Private m_bFirst As Boolean = True
   Private m_ButtonPower As New List(Of MachineButton)

   Private m_nCurrMode As Integer = 0

   Private Sub TestingPage_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
      StartBtn.Content = EgtMsg(90951)                   ' Start
      StopBtn.Content = EgtMsg(90952)                    ' Stop
      ResetBtn.Content = EgtMsg(90953)                   ' Reset
      AutoBtn.Content = EgtMsg(90954)                    ' Auto
      SingleBtn.Content = EgtMsg(90955)                  ' Single
      MDIBtn.Content = EgtMsg(90956)                     ' MDI
      ManualBtn.Content = EgtMsg(90957)                  ' Manual
      HomeBtn.Content = EgtMsg(90958)                    ' Home
      DownloadBtn.Content = EgtMsg(90959)                ' Download
      UploadBtn.Content = EgtMsg(90960)                  ' Upolad
      ActivateBtn.Content = EgtMsg(90961)                ' Activate
      DeleteBtn.Content = EgtMsg(90962)                  ' Delete
      MDIConfirmBtn.Content = EgtMsg(90963)              ' MDI Confirm
      CNModeGpBx.Header = EgtMsg(90964)                  ' Modalità CN
      CommandsGpBx.Header = EgtMsg(90965)                ' Comandi macchina
      MDICommandGpBx.Header = EgtMsg(90966)              ' Stringa MDI
      PartProgTransferGpBx.Header = EgtMsg(90967)        ' Trasferimento part program
      ErrorLstGpBx.Header = EgtMsg(90912)                ' Lista errori CN

      ' Attivo gruppo PartProgTransferGpBx leggendo la variabile nel file ini
      If GetPrivateProfileInt(S_GENERAL, K_TESTINGPAGE, 0, m_MainWindow.GetIniFile()) = 1 Then
         PartProgTransferGpBx.Visibility = Windows.Visibility.Visible
      Else
         PartProgTransferGpBx.Visibility = Windows.Visibility.Hidden
      End If

      ' Se prevista, scelta invio speciale part program
      Dim nSpecialSend As Integer = GetPrivateProfileInt(S_NUMERICALCONTROL, K_SPECIALSEND, -1, m_MainWindow.GetMachIniFile())
      If nSpecialSend <> -1 Then
         SpecialSendChBx.IsChecked() = (nSpecialSend = 1)
         SpecialSendGpBx.Header = "Special Send"
         SpecialSendGpBx.Visibility = Visibility.Visible
      else
         SpecialSendGpBx.Visibility = Visibility.Collapsed
      End If

      ' nuovi pulsanti
      If GetPrivateProfileInt(S_NCDATA, K_NEWCONSOLE, 0, m_MainWindow.GetMachIniFile()) = 1 Then
         PowerONBtn.Content = "ON"
         PowerOFFBtn.Content = "OFF"
         PowerGpBx.Header = EgtMsg(90974)    'Power
      Else
         PowerGpBx.Visibility = Visibility.Collapsed
      End If

      ' verifico che sia attiva la modalità per l'uso di due fotocamere
      If GetPrivateProfileInt(S_CAMERAHQ, K_CAMERAHQ_ENABLE, 0, m_MainWindow.GetMachIniFile()) = 1 Then
         CameraHQ.Visibility = Visibility.Visible
         CameraHQ.Header = EgtMsg(90975)     'Photo on table
         CameraHQBtn.Content = "HQ"
         ' verifico quale camera è impostata
         If GetPrivateProfileInt(S_CAMERAHQ, K_CAMERAHQ_ACTIVATE, 0, m_MainWindow.GetMachIniFile()) = 1 Then
            CameraHQBtn.IsChecked = True
            If Not IsNothing(m_MainWindow.m_CadCutPageUC.PhotoIMG) Then
               m_MainWindow.m_CadCutPageUC.PhotoIMG.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/Resources/NewIcons/icone-tagli-1HQ.png", UriKind.Relative))
            End If
         Else
            CameraHQBtn.IsChecked = False
            If Not IsNothing(m_MainWindow.m_CadCutPageUC.PhotoIMG) Then
               m_MainWindow.m_CadCutPageUC.PhotoIMG.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/Resources/NewIcons/icone-tagli-1.png", UriKind.Relative))
            End If
         End If
      Else
         CameraHQ.Visibility = Visibility.Collapsed
      End If

   End Sub

   Private Sub TestingPage_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
      If m_MainWindow.m_CNCommunication.m_nNCType = 3 AndAlso m_MainWindow.m_CNCommunication.m_CN.m_IsSiemensOne Then
         HomeBtn.Visibility = Visibility.Collapsed
         SingleBtn.Visibility = Visibility.Collapsed
         PartProgTransferGpBx.Visibility = Windows.Visibility.Hidden
      End If

      ' gestione visuliazzazione ToggleButton Auto/Sinlge/Mdi/Manula/Home
      SetCncMode()

      '------ NUOVI BOTTONI ----------
      ' Lettura configurazione bottoni (per impostare l'uso del Joystick) da Ini di macchina
      m_ButtonPower.Clear()
      Dim m_nCount As Integer = 1
      Dim bFoundBtn As Boolean = True
      Dim sTestVal As String = String.Empty
      ' se non trovo il primo pulsante della lista allora nascondo l'elenco dei pulsanti per accensione
      If GetPrivateProfileString("MachineButtons", K_BUTTON & "1", "", sTestVal, m_MainWindow.GetMachIniFile()) = 0 Then
         PowerGpBx.Visibility = Visibility.Collapsed
         Return
      End If
      While bFoundBtn
         Dim sNameBtn As String = K_BUTTON & (m_nCount).ToString()
         Dim sMachineButtonType As String = String.Empty
         Dim sTImageName As String = String.Empty
         Dim sTLuaScriptName As String = String.Empty
         Dim sFImageName As String = String.Empty
         Dim sFLuaScriptName As String = String.Empty
         Dim sStateFlag As String = String.Empty
         bFoundBtn = m_MainWindow.m_DirectCutPageUC.m_ControlsMachineButton.GetPrivateProfileMachineButtons("MachineButtons", sNameBtn, sMachineButtonType, sTImageName, sTLuaScriptName, sFImageName, sFLuaScriptName, sStateFlag, m_MainWindow.GetMachIniFile())
         If bFoundBtn Then
            m_nCount += 1
            Dim ButtonToAdd As MachineButton = Nothing
            ' la selezione dei comandi si trova nella pagina m_ControlsMachineButton.MachineButtonType (tipo Enum)
            Select Case sMachineButtonType
               Case 1
                  ButtonToAdd = New NoStateButton(sTImageName, sTLuaScriptName, sFImageName, sFLuaScriptName, sStateFlag)
               Case 2
                  ButtonToAdd = New TwoStateButton(sTImageName, sTLuaScriptName, sFImageName, sFLuaScriptName, sStateFlag)
               Case 3
                  ButtonToAdd = New ThreeStateButton(sTImageName, sTLuaScriptName, sFImageName, sFLuaScriptName, sStateFlag)
               Case 4
                  ButtonToAdd = New DoubleCommandButton(sTImageName, sTLuaScriptName, sFImageName, sFLuaScriptName, sStateFlag)
               Case 5
                  ButtonToAdd = New PressedCommandButton(sTImageName, sTLuaScriptName, sFImageName, sFLuaScriptName, sStateFlag)
            End Select
            If Not IsNothing(ButtonToAdd) Then
               m_ButtonPower.Add(ButtonToAdd)
            End If
         End If
      End While
      ' lo stato di questi comandi vieni carico dalla lettura del PLC (refresh)

      '-----------NUOVI BOTTONI------------

   End Sub

   Private Sub SetCncMode()
      Dim Mode As Integer = m_nCurrMode
      Select Case Mode
         Case 0
            ' Auoto
            MDIConfirmBtn.IsEnabled = False
            AutoBtn.IsChecked = True
            SingleBtn.IsChecked = False
            MDIBtn.IsChecked = False
            ManualBtn.IsChecked = False
            HomeBtn.IsChecked = False
         Case 1
            ' Single
            MDIConfirmBtn.IsEnabled = False
            AutoBtn.IsChecked = False
            SingleBtn.IsChecked = True
            MDIBtn.IsChecked = False
            ManualBtn.IsChecked = False
            HomeBtn.IsChecked = False
         Case 2
            ' Mdi
            MDIConfirmBtn.IsEnabled = True
            AutoBtn.IsChecked = False
            SingleBtn.IsChecked = False
            MDIBtn.IsChecked = True
            ManualBtn.IsChecked = False
            HomeBtn.IsChecked = False
         Case 7
            ' Manual
            MDIConfirmBtn.IsEnabled = False
            AutoBtn.IsChecked = False
            SingleBtn.IsChecked = False
            MDIBtn.IsChecked = False
            ManualBtn.IsChecked = True
            HomeBtn.IsChecked = False
         Case 8
            ' Home
            MDIConfirmBtn.IsEnabled = False
            AutoBtn.IsChecked = False
            SingleBtn.IsChecked = False
            MDIBtn.IsChecked = False
            ManualBtn.IsChecked = False
            HomeBtn.IsChecked = True
      End Select

   End Sub

   Private Sub StartBtn_Click(sender As Object, e As RoutedEventArgs) Handles StartBtn.Click
      If m_MainWindow.m_CNCommunication.m_nNCType = 3 AndAlso m_MainWindow.m_CNCommunication.m_CN.m_IsSiemensOne Then
         Dim sDBVarPath As String = ""
         GetPrivateProfileString(S_NCSIEMENS, K_DBVARPATH, "", sDBVarPath, m_MainWindow.GetMachIniFile)
         sDBVarPath &= EgtMsg(90976)                                     ' Start_Cycle
         m_CN.DVariables_WriteVariables3(sDBVarPath, 1, 1, 0, 0, "")     ' Modalità manuale
      Else
         m_CN.DGeneralFunctions_CycleStart()
      End If
   End Sub

   Private Sub StopBtn_Click(sender As Object, e As RoutedEventArgs) Handles StopBtn.Click
      If m_MainWindow.m_CNCommunication.m_nNCType = 3 AndAlso m_MainWindow.m_CNCommunication.m_CN.m_IsSiemensOne Then
         Dim sDBVarPath As String = ""
         GetPrivateProfileString(S_NCSIEMENS, K_DBVARPATH, "", sDBVarPath, m_MainWindow.GetMachIniFile)
         sDBVarPath &= EgtMsg(90977)                                     ' Stop_Cycle
         m_CN.DVariables_WriteVariables3(sDBVarPath, 1, 0, 0, 0, "")     ' Modalità manuale
      Else
         m_CN.DGeneralFunctions_FeedHold()
      End If
   End Sub

   Private Sub ResetBtn_Click(sender As Object, ghe As RoutedEventArgs) Handles ResetBtn.Click
      If m_MainWindow.m_CNCommunication.m_nNCType = 3 AndAlso m_MainWindow.m_CNCommunication.m_CN.m_IsSiemensOne Then
         Dim sDBVarPath As String = ""
         GetPrivateProfileString(S_NCSIEMENS, K_DBVARPATH, "", sDBVarPath, m_MainWindow.GetMachIniFile)
         sDBVarPath &= EgtMsg(90978)                                     ' Reset_Cycle
         m_CN.DVariables_WriteVariables3(sDBVarPath, 1, 1, 0, 0, "")     ' Modalità manuale
      Else
         Call m_CN.DGeneralFunctions_Reset()
      End If
   End Sub

   Private Sub AutoBtn_Click(sender As Object, e As RoutedEventArgs) Handles AutoBtn.Click
      m_CN.DGeneralFunctions_WriteCncMode(0)
   End Sub

   Private Sub SingleBtn_Click(sender As Object, e As RoutedEventArgs) Handles SingleBtn.Click
      m_CN.DGeneralFunctions_WriteCncMode(1)
   End Sub

   Private Sub MDIBtn_Click(sender As Object, e As RoutedEventArgs) Handles MDIBtn.Click
      m_CN.DGeneralFunctions_WriteCncMode(2)
   End Sub

   Private Sub ManualBtn_Click(sender As Object, e As RoutedEventArgs) Handles ManualBtn.Click
      m_CN.DGeneralFunctions_WriteCncMode(7)
   End Sub

   Private Sub HomeBtn_Click(sender As Object, e As RoutedEventArgs) Handles HomeBtn.Click
      m_CN.DGeneralFunctions_WriteCncMode(8)
   End Sub

   Private Sub CameraHQBtn_Click(sender As Object, e As RoutedEventArgs) Handles CameraHQBtn.Click
      Dim sEnableHQ As String = If(CameraHQBtn.IsChecked, "1", "0")
      WritePrivateProfileString(S_CAMERAHQ, K_CAMERAHQ_ACTIVATE, sEnableHQ, m_MainWindow.GetMachIniFile())
      If CameraHQBtn.IsChecked Then
         If Not IsNothing(m_MainWindow.m_CadCutPageUC.PhotoIMG) Then
            m_MainWindow.m_CadCutPageUC.PhotoIMG.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/Resources/NewIcons/icone-tagli-1HQ.png", UriKind.Relative))
         End If
      Else
         If Not IsNothing(m_MainWindow.m_CadCutPageUC.PhotoIMG) Then
            m_MainWindow.m_CadCutPageUC.PhotoIMG.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/Resources/NewIcons/icone-tagli-1.png", UriKind.Relative))
         End If
      End If
   End Sub

   Private Sub MDITxBx_KeyDown(sender As Object, e As KeyEventArgs) Handles MDITxBx.KeyDown
      If e.Key = Key.Return Then
         ' leggo se stato reset
         If Not m_CN.bResetState Then Return
         m_CN.sz_ManualDataInput = MDITxBx.Text
         ' se attivi nuovi comandi MDI su siemens
         If m_MainWindow.m_CNCommunication.m_nNCType = 3 AndAlso GetPrivateProfileInt(S_NCSIEMENS, K_USENEWMDI, 0, m_MainWindow.GetMachIniFile()) > 0 Then
            EgtOutLog("MDI command: " & m_CN.sz_ManualDataInput)
            Dim x = m_CN.New_MDI_command(1)
            EgtOutLog("MDI command res: " & x)
         Else
            m_CN.MDI_command()
         End If
         MDITxBx.Background = Brushes.LightGray
         'Keyboard.ClearFocus()
      End If
   End Sub

   Private Sub MDITxBx_PreviewMouseDown(sender As Object, e As MouseButtonEventArgs) Handles MDITxBx.PreviewMouseDown
      MDITxBx.Background = Brushes.White
   End Sub

   Friend Sub DownloadBtn_Click(sender As Object, e As RoutedEventArgs) Handles DownloadBtn.Click
      If m_MainWindow.m_CNCommunication.m_nNCType = 1 Then
         m_CN.Delete_NC_prog(DULoadTxBx.Text)
      End If
      Dim DownloadName As String = String.Empty
      If m_MainWindow.m_CNCommunication.m_nNCType = 1 Or m_MainWindow.m_CNCommunication.m_nNCType = 2 Then
         DownloadName = "%" & DULoadTxBx.Text
      Else
         DownloadName = DULoadTxBx.Text
      End If
      Dim sPcFile As String = m_MainWindow.GetCncDir() & "\" & DULoadTxBx.Text & m_MainWindow.m_CurrentMachine.sIsoFileExt
      m_CN.Download_NC_prog(sPcFile, DownloadName)
   End Sub

   Private Sub UploadBtn_Click(sender As Object, e As RoutedEventArgs) Handles UploadBtn.Click
      Dim DownloadName As String = String.Empty
      If m_MainWindow.m_CNCommunication.m_nNCType = 1 Or m_MainWindow.m_CNCommunication.m_nNCType = 2 Then
         DownloadName = "%" & DULoadTxBx.Text
      Else
         DownloadName = DULoadTxBx.Text
      End If
      Dim sPcFile As String = m_MainWindow.GetCncDir() & "\" & DULoadTxBx.Text & m_MainWindow.m_CurrentMachine.sIsoFileExt
      m_CN.Upload_NC_prog(sPcFile, DownloadName)
   End Sub

   Private Sub ActivateBtn_Click(sender As Object, e As RoutedEventArgs) Handles ActivateBtn.Click
      If m_MainWindow.m_CNCommunication.m_nNCType = 1 Or m_MainWindow.m_CNCommunication.m_nNCType = 2 Then
         Dim nName As Integer = 0
         StringToInt(DULoadTxBx.Text, nName)
         m_CN.ActivateProgram(nName)             ' integer version
      Else
         m_CN.ActivateProgram(DULoadTxBx.Text)   ' string version
      End If
   End Sub

   Private Sub DeleteBtn_Click(sender As Object, e As RoutedEventArgs) Handles DeleteBtn.Click
      Dim DeleteName As String = String.Empty
      If m_MainWindow.m_CNCommunication.m_nNCType = 1 Or m_MainWindow.m_CNCommunication.m_nNCType = 2 Then
         DeleteName = "%" & DULoadTxBx.Text
      Else
         DeleteName = DULoadTxBx.Text
      End If
      m_CN.Delete_NC_prog(DeleteName)
   End Sub

   Private Sub MDIConfirmBtn_Click(sender As Object, e As RoutedEventArgs) Handles MDIConfirmBtn.Click
      m_CN.sz_ManualDataInput = MDITxBx.Text
      ' se attivi nuovi comandi MDI su siemens
      If m_MainWindow.m_CNCommunication.m_nNCType = 3 AndAlso GetPrivateProfileInt(S_NCSIEMENS, K_USENEWMDI, 0, m_MainWindow.GetMachIniFile()) > 0 Then
         ' leggo se stato reset
         If Not m_CN.bResetState Then Return
         EgtOutLog("MDI command: " & m_CN.sz_ManualDataInput)
         Dim x = m_CN.New_MDI_command(1)
         EgtOutLog("MDI command res: " & x)
      Else
         m_CN.MDI_command()
      End If

      MDITxBx.Background = Brushes.LightGray
   End Sub

   Private Sub SpecialSend_Click(sender As Object, e As RoutedEventArgs) Handles SpecialSendChBx.Click
      m_MainWindow.m_CNCommunication.SpecialSend() = If( SpecialSendChBx.IsChecked(), 1, 0)
   End Sub

   Private Sub PowerON_Click(sender As Object, e As RoutedEventArgs) Handles PowerONBtn.Click
      Dim PowerOnButton As MachineButton = m_ButtonPower(0)
      ' eseguo lo script lua associato
      PowerOnButton.ExecuteMDICommand(PowerOnButton.TLuaScriptName)
      ' che comunica al PLC di cambiare lo stato, la modifica dello stato è intercettata dalla funzione Refresh che avvia il metodo Changed
   End Sub

   Private Sub PowerOFF_Click(sender As Object, e As RoutedEventArgs) Handles PowerOFFBtn.Click
      Dim PowerOffButton As MachineButton = m_ButtonPower(1)
      ' eseguo lo script lua associato
      PowerOffButton.ExecuteMDICommand(PowerOffButton.TLuaScriptName)
      ' che comunica al PLC di cambiare lo stato, la modifica dello stato è intercettata dalla funzione Refresh che avvia il metodo Changed
   End Sub

   Friend Sub PowerONChanged(bPowerON As Boolean)
      ' devo decodificare il tipo di pulsante, quindi eseguire la conversione...
      Dim PowerONButton As TwoStateButton = Nothing
      For Each MachineButton As MachineButton In m_ButtonPower
         If MachineButton.StateFlag.Trim = K_POWERON Then
            PowerONButton = MachineButton
            Exit For
         End If
      Next
      If Not IsNothing(PowerONButton) Then
         PowerONButton.SetIsChecked(bPowerON)
         PowerONBtn.IsChecked = bPowerON
      End If
   End Sub

   Friend Sub PowerOFFChanged(bPowerOFF As Boolean)
      ' leggo solo una varibile -> quindi quando modifico lo stato di PowerON devo modificare lo stato di PowerOFF
      Dim PowerOFFButton As TwoStateButton = Nothing
      For Each MachineButton As MachineButton In m_ButtonPower
         If MachineButton.StateFlag.Trim = K_POWEROFF Then
            PowerOFFButton = MachineButton
            Exit For
         End If
      Next
      If Not IsNothing(PowerOFFButton) Then
         PowerOFFButton.SetIsChecked(bPowerOFF)
         PowerOFFBtn.IsChecked = bPowerOFF
      End If
   End Sub

   Friend Sub CncModeChange(nMode As Integer)
      m_nCurrMode = nMode
      SetCncMode()
   End Sub

End Class
