Imports EgtUILib

Public Class MachineButtonsUC

   'Riferimento alla MainWindow
   Dim m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
   Private m_DirectCutPage As DirectCutPageUC
   Friend m_CN As CN_generico

   Private m_bOnlyLaser As Boolean = False
   Private m_bFirst As Boolean = True

   ' 9/2 aggiunto spazio per un nuovo bottone
   Private Const MAX_BUTTONS As Integer = 11
   Private m_nCount As Integer = 0
   Private ImageArrayY(MAX_BUTTONS - 1) As String
   Private ImageArrayN(MAX_BUTTONS - 1) As String
   Private CommandArrayY(MAX_BUTTONS - 1) As String
   Private CommandArrayN(MAX_BUTTONS - 1) As String
   Private StateFlagArray(MAX_BUTTONS - 1) As String

   ' Creazione converter da String a ImageSource
   Dim ImageConverter As New ImageSourceConverter

   ' Costanti per nomi stati dei bottoni
   Private Const BTN_STATE_SPINDLE As String = "Spindle"
   Private Const BTN_STATE_COOLANT As String = "Coolant"
   Private Const BTN_STATE_LASER As String = "Laser"
   Private Const BTN_STATE_LASERTRAC As String = "LaserTrac"
   Private Const BTN_STATE_THREEAXIS As String = "ThreeAxis"
   Private Const BTN_STATE_FIVEAXIS As String = "FiveAxis"
   Private Const BTN_STATE_NOTHING As String = "Nothing"
   Private Const BTN_STATE_DOOR_OPENED As String = "DoorOpened"
   Private Const BTN_STATE_DOOR_CLOSED As String = "DoorClosed"
   Private Const BTN_STATE_PARKING As String = "Parking"
   Private Const BTN_ENABLE_ZONE_1 As String = "EnableZone1"
   Private Const BTN_ENABLE_ZONE_2 As String = "EnableZone2"
   Private Const BTN_ENABLE_PC As String = "EnablePC"

   Public Sub New(Optional bOnlyLaser As Boolean = False)
      ' This call is required by the designer.
      InitializeComponent()
      ' Imposto
      m_bOnlyLaser = bOnlyLaser
   End Sub

   Private Sub MachineButtons_Loaded(sender As Object, e As RoutedEventArgs)

      If m_bFirst Then
         m_DirectCutPage = m_MainWindow.m_DirectCutPageUC
         m_bFirst = False
      End If

      ' Lettura configurazione bottoni da Ini di macchina
      Dim m_nCount As Integer = 0
      For nIndex As Integer = 0 To MAX_BUTTONS - 1
         Dim sButton As String = K_BUTTON & (nIndex + 1).ToString()
         Dim sButtonImage As String = String.Empty
         Dim sButtonCommand As String = String.Empty
         Dim sButtonStateFlag As String = String.Empty
         If GetPrivateProfileMachineButtons(S_MACHBUTTONS, sButton & "Y", sButtonImage, sButtonCommand, sButtonStateFlag, m_MainWindow.GetMachIniFile()) And
            (Not m_bOnlyLaser Or sButtonStateFlag = BTN_STATE_LASER) Then
            ImageArrayY(m_nCount) = sButtonImage
            CommandArrayY(m_nCount) = sButtonCommand
            StateFlagArray(m_nCount) = sButtonStateFlag
            If GetPrivateProfileMachineButtons(S_MACHBUTTONS, sButton & "N", sButtonImage, sButtonCommand, sButtonStateFlag, m_MainWindow.GetMachIniFile()) Then
               ImageArrayN(m_nCount) = sButtonImage
               CommandArrayN(m_nCount) = sButtonCommand
            End If
            m_nCount += 1
         End If
      Next

      ' Nascondo bottoni inutilizzati
      For nIndex As Integer = m_nCount To MAX_BUTTONS - 1
         GetToggleButton(nIndex + 1).Visibility = Windows.Visibility.Hidden
      Next

      ' Se variabile di stato "Nothing"/"DoorOpened"/"DoorClosed" imposto immagine fissa
      For nIndex As Integer = 0 To m_nCount - 1
         If StateFlagArray(nIndex) = BTN_STATE_NOTHING OrElse
            StateFlagArray(nIndex) = BTN_STATE_DOOR_OPENED OrElse
            StateFlagArray(nIndex) = BTN_STATE_DOOR_CLOSED OrElse
            StateFlagArray(nIndex) = BTN_ENABLE_PC OrElse
            StateFlagArray(nIndex) = BTN_ENABLE_ZONE_1 OrElse
            StateFlagArray(nIndex) = BTN_ENABLE_ZONE_2 Then
            ' mostra immagine fissa
            Try
               Dim s As String
               If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
                  s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
               Else
                  s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
               End If
               'Dim s As String = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
               Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
               GetImage(nIndex + 1).Source = sButtonImageSource
            Catch ex As Exception
               EgtOutLog("Error loading image " & ImageArrayY(nIndex))
            End Try
         End If
      Next

      ' Se non collegato a CN metto immagini fisse (o nessuna  immagine)  
      If Not m_MainWindow.m_bNCLink Then
         For nIndex As Integer = 0 To m_nCount - 1
            Dim sImage As String = If(String.IsNullOrEmpty(ImageArrayN(nIndex)), ImageArrayY(nIndex), ImageArrayN(nIndex))
            If Not String.IsNullOrEmpty(sImage) Then
               Try
                  Dim s As String
                  If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
                     s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & sImage
                  Else
                     s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & sImage
                  End If
                  'Dim s As String = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & sImage
                  Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
                  GetImage(nIndex + 1).Source = sButtonImageSource
               Catch ex As Exception
                  EgtOutLog("Error loading image " & sImage)
               End Try
            Else
               ' In attesa che attivono le icone di questi pulsanti scrivo il contenuto del bottone
               Try
                  Dim CurrToggleBtn As Primitives.ToggleButton = GetToggleButton(nIndex + 1)
                  If StateFlagArray(nIndex) = K_XYJOG Then
                     CurrToggleBtn.Content = "X - Y"
                  ElseIf StateFlagArray(nIndex) = K_ZCJOG Then
                     CurrToggleBtn.Content = "Z - C"
                  ElseIf StateFlagArray(nIndex) = K_ZBJOG Then
                     CurrToggleBtn.Content = "Z - B"
                  ElseIf StateFlagArray(nIndex) = K_REMOTE Then
                     CurrToggleBtn.Content = "Remote"
                  End If
               Catch ex As Exception
                  EgtOutLog("Error loading content " & StateFlagArray(nIndex))
               End Try
            End If
         Next
      End If

   End Sub

   Private Sub MachineButton_Click(sender As Object, e As RoutedEventArgs) Handles MachineButton1.Click, MachineButton2.Click, MachineButton3.Click, MachineButton4.Click, MachineButton5.Click,
                                                                                   MachineButton6.Click, MachineButton7.Click, MachineButton8.Click, MachineButton9.Click, MachineButton10.Click,
                                                                                   MachineButton11.Click
      Dim CurrentBtn As Primitives.ToggleButton = e.Source
      ' recupero l'inidce del bottone selezionato
      Dim nIndex As Integer = GetToggleButtonIndex(CurrentBtn) - 1

      Dim sBaseDir As String = m_MainWindow.m_CurrentMachine.sMachDir & "\DirectCmd\"
      Dim sLuaFileName As String = String.Empty

      ' Se il bottone chiamantè quello delle porte allora devo eseguire due comandi MDI
      If nIndex = Array.IndexOf(StateFlagArray, BTN_STATE_DOOR_OPENED) OrElse
         nIndex = Array.IndexOf(StateFlagArray, BTN_STATE_DOOR_CLOSED) Then
         Dim sTLuaFile As String = sBaseDir & CommandArrayY(nIndex)
         Dim sFLuaFile As String = sBaseDir & CommandArrayN(nIndex)
         ExecuteMDICommand(CurrentBtn, sTLuaFile)
         ExecuteMDICommand(CurrentBtn, sFLuaFile)
         CurrentBtn.IsChecked = False
         Return
      End If

      ' Se il bottone chiamantè quello per la selezione del pannello di controllo
      If nIndex = Array.IndexOf(StateFlagArray, BTN_ENABLE_PC) Then
         Dim sTLuaFile As String = sBaseDir & CommandArrayY(nIndex)
         Dim sFLuaFile As String = sBaseDir & CommandArrayN(nIndex)
         If m_CN.nEnablePc = 1 Then
            ExecuteMDICommand(CurrentBtn, sTLuaFile)
         ElseIf m_CN.nEnablePc = 2 Then
            ExecuteMDICommand(CurrentBtn, sFLuaFile)
         End If
         Return
      End If

      If CurrentBtn.IsChecked() Then
         'EgtLuaExecFile(sBaseDir & CommandArrayY(nIndex))
         sLuaFileName = sBaseDir & CommandArrayY(nIndex)
      Else
         If Not (StateFlagArray(nIndex) = BTN_STATE_THREEAXIS Or
                 StateFlagArray(nIndex) = BTN_STATE_FIVEAXIS) Then
            'EgtLuaExecFile(sBaseDir & CommandArrayN(nIndex))
            sLuaFileName = sBaseDir & CommandArrayN(nIndex)
         Else
            Return
         End If
      End If

      ExecuteMDICommand(CurrentBtn, sLuaFileName)

      ' se non ha stato e quindi è un bottone normale, tolgo il check
      If StateFlagArray(nIndex) = BTN_STATE_NOTHING Then
         CurrentBtn.IsChecked = False
      End If

   End Sub

   Friend Sub ExecuteMDICommand(CurrentBtn As Primitives.ToggleButton, sLuaFileName As String)
      If String.IsNullOrWhiteSpace(sLuaFileName) Then Return
      Dim CmdString As String = String.Empty
      Dim b2Start As Boolean = False
      Dim EActive As Boolean = False
      Dim ENumber As String = String.Empty
      Dim EValue As String = String.Empty
      Dim EType As String = 0
      Dim ENumber2 As String = String.Empty
      Dim EValue2 As String = String.Empty
      Dim EType2 As String = 0
      ' eseguo la lettura del file .lua associato al comando
      ExecuteDirectCmdLua(sLuaFileName, CmdString, b2Start, EActive, ENumber, EValue, EType, ENumber2, EValue2, EType2)
      ' comunico i dati calcolati al PLC (quidni ignoro eventuali comandi MDI), scrivo messaggio MDI
      If EActive Then
         Select Case m_MainWindow.m_CNCommunication.m_nNCType
            Case 1, 2
               If m_CN.m_NewVariable And m_MainWindow.m_CNCommunication.m_nNCType = 2 Then
                  ' solo per Flexium
                  m_CN.DPlcVariables_WriteVariables(ENumber, EValue)
                  If Not IsNothing(ENumber2) And Not IsNothing(EValue2) Then
                     m_CN.DPlcVariables_WriteVariables(ENumber2, EValue2)
                  End If
                  ' altrimenti scrittura delle variabili E
               Else
                  m_CN.DVariables_WriteVariables2(ENumber, EValue)
               End If
               Return
            Case 3
               If m_MainWindow.m_DirectCutPageUC.m_NewMachineButtonsType Then
                  ' scrivo prima variabile
                  Select Case CShort(EType)
                     Case 1
                        m_CN.DVariables_WriteVariables3(ENumber, CShort(EType), CInt(EValue), 0, 0, "")
                        EgtOutLog("ENumber= " & ENumber & "EType= " & CShort(EType) & "EValue= " & CInt(EValue))
                     Case 2
                        m_CN.DVariables_WriteVariables3(ENumber, CShort(EType), 0, CLng(EValue), 0, "")
                        EgtOutLog("ENumber= " & ENumber & "EType= " & CShort(EType) & "EValue= " & CLng(EValue))
                     Case 3
                        Dim d As Double = 0
                        StringToDouble(EValue, d)
                        m_CN.DVariables_WriteVariables3(ENumber, CShort(EType), 0, 0, d, "")
                        EgtOutLog("ENumber= " & ENumber & "EType= " & CShort(EType) & "EValue= " & d)
                     Case 4
                        m_CN.DVariables_WriteVariables3(ENumber, CShort(EType), 0, 0, 0, EValue)
                        EgtOutLog("ENumber= " & ENumber & "EType= " & CShort(EType) & "EValue= " & EValue)
                  End Select
                  EgtOutLog("dopo scrittura prima variabile")
                  If Not IsNothing(EType2) AndAlso CShort(EType) > 0 Then
                     System.Threading.Thread.Sleep(100)
                     ' scrivo seconda variabile
                     Select Case CShort(EType2)
                        Case 1
                           m_CN.DVariables_WriteVariables3(ENumber2, CShort(EType2), CInt(EValue2), 0, 0, "")
                           EgtOutLog("ENumber2= " & ENumber2 & "EType2= " & CShort(EType2) & "EValue2= " & CInt(EValue2))
                        Case 2
                           m_CN.DVariables_WriteVariables3(ENumber2, CShort(EType2), 0, CLng(EValue2), 0, "")
                           EgtOutLog("ENumber2= " & ENumber2 & "EType2= " & CShort(EType2) & "EValue2= " & CLng(EValue2))
                        Case 3
                           Dim d As Double = 0
                           StringToDouble(EValue2, d)
                           m_CN.DVariables_WriteVariables3(ENumber2, CShort(EType2), 0, 0, d, "")
                           EgtOutLog("ENumber2= " & ENumber2 & "EType2= " & CShort(EType2) & "EValue2= " & d)
                        Case 4
                           m_CN.DVariables_WriteVariables3(ENumber2, CShort(EType2), 0, 0, 0, EValue2)
                           EgtOutLog("ENumber2= " & ENumber2 & "EType2= " & CShort(EType2) & "EValue2= " & EValue2)
                     End Select
                     EgtOutLog("dopo scrittura seconda variabile")
                  End If
                  Return
               End If
         End Select
      End If

      Dim nResult As Short
      ' Imposto modalità MDI per controlli num
      Select Case m_MainWindow.m_CNCommunication.m_nNCType
         Case 1, 2
            nResult = m_CN.DGeneralFunctions_WriteCncMode(2)
         Case 3
            'Per il siemens non devo fare nulla
      End Select
      m_CN.sz_ManualDataInput = CmdString
      m_CN.MDI_command()
      Select Case m_MainWindow.m_CNCommunication.m_nNCType
         Case 1, 2
            System.Threading.Thread.Sleep(300)
            m_CN.DGeneralFunctions_CycleStart()
         Case 3
            'Per il siemens non devo fare nulla
      End Select

      If b2Start Then
         System.Threading.Thread.Sleep(800)
         m_CN.DGeneralFunctions_CycleStart()
      End If
      System.Threading.Thread.Sleep(300)
      nResult = m_CN.DGeneralFunctions_WriteCncMode(7)     ' Modalità manuale
   End Sub

   ' questa è una copia della funzione presente nel codice ControlsMachineButtonUC.xaml.vb
   Friend Sub ExecuteDirectCmdLua(LuaFileName As String, ByRef CmdString As String, ByRef b2Start As Boolean, ByRef EActive As Boolean, ByRef ENumber As String, ByRef EValue As String, ByRef EType As String, ByRef ENumber2 As String, ByRef EValue2 As String, ByRef EType2 As String)
      'Dim sBaseDir As String = m_MainWindow.m_CurrentMachine.sMachDir & "\DirectCmd\"
      If EgtLuaExecFile(LuaFileName) Then
         EgtOutLog("Lua " & LuaFileName & " eseguito")
      Else
         EgtOutLog("Lua " & LuaFileName & " non eseguito")
      End If
      Dim dFeed As Double = 0
      If Not String.IsNullOrWhiteSpace(m_DirectCutPage.m_ManualAxesMove.FeedTxBx.Text) Then
         StringToLen(m_DirectCutPage.m_ManualAxesMove.FeedTxBx.Text, dFeed)
      Else
         EgtTdbSetCurrTool(m_MainWindow.m_CurrentProjectPageUC.ToolTxBx.Text)
         EgtTdbGetCurrToolParam(MCH_TP.FEED, dFeed)
      End If
      EgtLuaSetGlobNumVar("CMD.F", dFeed)
      Dim dSpeed As Double = 0
      If Not String.IsNullOrWhiteSpace(m_DirectCutPage.m_ManualAxesMove.SpeedTxBx.Text) Then
         StringToDouble(m_DirectCutPage.m_ManualAxesMove.SpeedTxBx.Text, dSpeed)
      Else
         EgtTdbSetCurrTool(m_MainWindow.m_CurrentProjectPageUC.ToolTxBx.Text)
         EgtTdbGetCurrToolParam(MCH_TP.SPEED, dSpeed)
      End If
      EgtLuaSetGlobNumVar("CMD.S", dSpeed)
      Dim dL1, dL2, dL3, dR1, dR2 As Double
      m_MainWindow.m_CNCommunication.GetAxesPositions(dL1, dL2, dL3, dR1, dR2)
      EgtLuaSetGlobNumVar("CMD.L1", dL1)
      EgtLuaSetGlobNumVar("CMD.L2", dL2)
      EgtLuaSetGlobNumVar("CMD.L3", dL3)
      EgtLuaSetGlobNumVar("CMD.R1", dR1)
      EgtLuaSetGlobNumVar("CMD.R2", dR2)
      EgtLuaSetGlobBoolVar("CMD.INCHES", m_MainWindow.m_CNCommunication.GetMachineInInches())
      EgtLuaCallFunction("CmdString")
      ' Leggo variabili
      CmdString = String.Empty
      EgtLuaGetGlobStringVar("CMD.CMDSTRING", CmdString)
      b2Start = False
      EgtLuaGetGlobBoolVar("CMD.DOUBLESTART", b2Start)
      EActive = False
      EgtLuaGetGlobBoolVar("CMD.EACTIVE", EActive)
      ENumber = String.Empty
      EgtLuaGetGlobStringVar("CMD.ENUMBER", ENumber)
      EValue = String.Empty
      EgtLuaGetGlobStringVar("CMD.EVALUE", EValue)
      EType = String.Empty
      EgtLuaGetGlobStringVar("CMD.ETYPE", EType)
      EgtOutLog("ENUMBER: " & ENumber & " EVALUE: " & EValue & " ETYPE: " & EType)
      ENumber2 = String.Empty
      EgtLuaGetGlobStringVar("CMD.ENUMBER2", ENumber2)
      EValue2 = String.Empty
      EgtLuaGetGlobStringVar("CMD.EVALUE2", EValue2)
      EType2 = String.Empty
      EgtLuaGetGlobStringVar("CMD.ETYPE2", EType2)
      EgtOutLog("ENUMBER2: " & ENumber2 & " EVALUE2: " & EValue2 & " ETYPE2: " & EType2)
      ' Reset lua
      EgtLuaResetGlobVar("CmdString")
      EgtLuaResetGlobVar("CMD")
      ' Log del comando
      EgtOutLog("CmdString=" & If(Not String.IsNullOrEmpty(CmdString), CmdString, "") &
                " b2Start=" & b2Start.ToString() &
                " EActive=" & EActive.ToString &
                " ENumber=" & If(Not String.IsNullOrEmpty(ENumber), ENumber, "") &
                " EValue=" & If(Not String.IsNullOrEmpty(EValue), EValue, "") &
                " EType=" & If(Not String.IsNullOrEmpty(EType), CInt(EType).ToString, "") &
                " ENumber2=" & If(Not String.IsNullOrEmpty(ENumber2), ENumber2, "") &
                " EValue2=" & If(Not String.IsNullOrEmpty(EValue2), EValue2, "") &
                " EType2=" & If(Not String.IsNullOrEmpty(EType2), CInt(EType2).ToString, ""))
   End Sub

#Region "STATE CHANGED"

   Friend Sub SpindleStateChanged(SpindleState As Boolean)
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, BTN_STATE_SPINDLE)
      If nIndex = -1 Then Return
      If SpindleState Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayY(nIndex + 1))
         End Try
      Else
         GetToggleButton(nIndex + 1).IsChecked = False
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayN(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayN(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayN(nIndex + 1))
         End Try
      End If
   End Sub

   Friend Sub CoolantStateChanged(CoolantState As Boolean)
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, BTN_STATE_COOLANT)
      If nIndex = -1 Then Return
      If CoolantState Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayY(nIndex + 1))
         End Try
      Else
         GetToggleButton(nIndex + 1).IsChecked = False
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayN(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayN(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayN(nIndex + 1))
         End Try
      End If
   End Sub

   Friend Sub LaserStateChanged(LaserState As Boolean)
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, BTN_STATE_LASER)
      If nIndex = -1 Then Return
      If LaserState Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayY(nIndex + 1))
         End Try
      Else
         GetToggleButton(nIndex + 1).IsChecked = False
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayN(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayN(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayN(nIndex + 1))
         End Try
      End If
   End Sub

   Friend Sub LaserTracStateChanged(LaserState As Boolean)
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, BTN_STATE_LASERTRAC)
      If nIndex = -1 Then Return
      If LaserState Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayY(nIndex + 1))
         End Try
      Else
         GetToggleButton(nIndex + 1).IsChecked = False
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayN(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayN(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayN(nIndex + 1))
         End Try
      End If
   End Sub

   Friend Sub ThreeAxisStateChanged(ThreeAxisState As Boolean)
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, BTN_STATE_THREEAXIS)
      If nIndex = -1 Then Return
      If ThreeAxisState Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayY(nIndex + 1))
         End Try
      Else
         GetToggleButton(nIndex + 1).IsChecked = False
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayN(nIndex + 1))
         End Try
      End If
   End Sub

   Friend Sub FiveAxisStateChanged(FiveAxisState As Boolean)
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, BTN_STATE_FIVEAXIS)
      If nIndex = -1 Then Return
      If FiveAxisState Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayY(nIndex + 1))
         End Try
      Else
         GetToggleButton(nIndex + 1).IsChecked = False
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayN(nIndex + 1))
         End Try
      End If
   End Sub

   Friend Sub DoorStateChanged(DoorState As Integer)
      If IsNothing(DoorState) Then
         EgtOutLog("Error: door state null!")
         Return
      End If
      ' recupero le associazioni con i bottoni
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, BTN_STATE_DOOR_OPENED)
      If nIndex = -1 Then Return
      ' bottone di apertura porte
      Dim DoorOpenedButton As Primitives.ToggleButton = GetToggleButton(nIndex + 1)
      nIndex = Array.IndexOf(StateFlagArray, BTN_STATE_DOOR_CLOSED)
      If nIndex = -1 Then Return
      ' bottone di chiusura porte
      Dim DoorClosedButton As Primitives.ToggleButton = GetToggleButton(nIndex + 1)
      ' modifico il colore dei bottoni
      If Not IsNothing(DoorState) AndAlso Not IsNothing(DoorClosedButton) Then
         Select Case DoorState
            Case 0
               DoorClosedButton.Background = Application.Current.FindResource("OmagCut_Red")
            Case 1, 2
               DoorClosedButton.Background = Application.Current.FindResource("OmagCut_LightGray")
         End Select
      End If
      If Not IsNothing(DoorState) AndAlso Not IsNothing(DoorOpenedButton) Then
         Select Case DoorState
            Case 0
               DoorOpenedButton.Background = Application.Current.FindResource("OmagCut_LightGray")
            Case 1
               DoorOpenedButton.Background = Application.Current.FindResource("OmagCut_Yellow")
            Case 2
               DoorOpenedButton.Background = Application.Current.FindResource("OmagCut_Green")
         End Select
      End If
   End Sub

   Friend Sub ParkingStateChanged(ParkingState As Boolean)
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, BTN_STATE_PARKING)
      If nIndex = -1 Then Return
      If ParkingState Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayY(nIndex + 1))
         End Try
      Else
         GetToggleButton(nIndex + 1).IsChecked = False
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayN(nIndex + 1))
         End Try
      End If
   End Sub

   Friend Sub EnableZoneStateChanged(ZoneState As Integer)
      Dim sFlag As String = String.Empty
      If ZoneState = 1 Then
         sFlag = BTN_ENABLE_ZONE_1
      ElseIf ZoneState = 2 Then
         sFlag = BTN_ENABLE_ZONE_2
      End If
      ' recupero il bottone che deve essere acceso (quindi spengo l'altro)
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, sFlag)

      ' se non trovo nessun riferimento allora spengo entrambi i comandi
      If nIndex = -1 Then
         nIndex = Array.IndexOf(StateFlagArray, BTN_ENABLE_ZONE_1)
         GetToggleButton(nIndex + 1).IsChecked = False
         nIndex = Array.IndexOf(StateFlagArray, BTN_ENABLE_ZONE_2)
         GetToggleButton(nIndex + 1).IsChecked = False
         Return
      End If

      If ZoneState = 1 Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayY(nIndex + 1))
         End Try
         ' spengo l'altro bottone (lo stato dei due bottoni sono gestiti da una sola variabile)
         nIndex = Array.IndexOf(StateFlagArray, BTN_ENABLE_ZONE_2)
         GetToggleButton(nIndex + 1).IsChecked = False

      ElseIf ZoneState = 2 Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayN(nIndex + 1))
         End Try
         ' spengo l'altro bottone (lo stato dei due bottoni sono gestiti da una sola variabile)
         nIndex = Array.IndexOf(StateFlagArray, BTN_ENABLE_ZONE_1)
         GetToggleButton(nIndex + 1).IsChecked = False
      End If
   End Sub

   Friend Sub EnablePcStateChanged(PcState As Integer)
      ' il comando ButtonY accendo il Pannello_1, il comando ButtonN accendo il Pannello_2 (uno è la negazione dell'altro)
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, BTN_ENABLE_PC)
      If nIndex = -1 Then Return
      If PcState = 1 Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayY(nIndex + 1))
         End Try
      ElseIf PcState = 2 Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayN(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayN(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayN(nIndex + 1))
         End Try
      Else
         ' nessuno dei due pannelli attivo
         GetToggleButton(nIndex + 1).IsChecked = False
      End If
   End Sub

   Friend Sub TableUpChanged(TableUpState As Boolean)
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, K_TABLEUP)
      If nIndex = -1 Then Return
      If TableUpState Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayY(nIndex + 1))
         End Try
      Else
         GetToggleButton(nIndex + 1).IsChecked = False
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayN(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayN(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayN(nIndex + 1))
         End Try
      End If
   End Sub

   Friend Sub TableDownChanged(TableDownState As Boolean)
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, K_TABLEDOWN)
      If nIndex = -1 Then Return
      If TableDownState Then
         GetToggleButton(nIndex + 1).IsChecked = True
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayY(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayY(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayY(nIndex + 1))
         End Try
      Else
         GetToggleButton(nIndex + 1).IsChecked = False
         Try
            Dim s As String
            If (m_MainWindow.m_OptionsPageUC.ThemesCmBx.SelectedIndex = 0) Then
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\" & ImageArrayN(nIndex)
            Else
               s = m_MainWindow.GetResourcesDir() & "\MachineButtonsImage\NewIcons\" & ImageArrayN(nIndex)
            End If
            Dim sButtonImageSource As ImageSource = ImageConverter.ConvertFromString(s)
            GetImage(nIndex + 1).Source = sButtonImageSource
         Catch ex As Exception
            EgtOutLog("Error loading image " & ImageArrayN(nIndex + 1))
         End Try
      End If
   End Sub

   '----------------- Queste funzioni determina lo stato del bottone direttamente dalla lettura delle variabili CN
   Friend Sub XYJogChanged(ByVal bXYAxes As Boolean)
      ' recupero le asscociazioni con i bottoni
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, K_XYJOG)
      If nIndex = -1 Then Return
      ' selezoiono lo stato del bottone
      GetToggleButton(nIndex + 1).IsChecked = bXYAxes
   End Sub

   Friend Sub ZJogChanged(ByVal bZAxes As Boolean)
      ' recupero le asscociazioni con i bottoni
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, K_ZCJOG)
      If nIndex = -1 Then Return
      ' selezoiono lo stato del bottone
      GetToggleButton(nIndex + 1).IsChecked = bZAxes
   End Sub

   Friend Sub BCJogChanged(ByVal bBCAxes As Boolean)
      ' recupero le asscociazioni con i bottoni
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, K_ZBJOG)
      If nIndex = -1 Then Return
      ' selezoiono lo stato del bottone
      GetToggleButton(nIndex + 1).IsChecked = bBCAxes
   End Sub

   Friend Sub RemoteChanged(ByVal bRemote As Boolean)
      ' recupero le asscociazioni con i bottoni
      Dim nIndex As Integer = Array.IndexOf(StateFlagArray, K_REMOTE)
      If nIndex = -1 Then Return
      ' selezoiono lo stato del bottone
      GetToggleButton(nIndex + 1).IsChecked = bRemote
   End Sub

   '-----------------------------------------------------------------------------------------------------------------

#End Region    ' State changed

   Private Function GetToggleButton(ByVal nIndex As Integer) As Primitives.ToggleButton
      Select Case nIndex
         Case 1
            Return MachineButton1
         Case 2
            Return MachineButton2
         Case 3
            Return MachineButton3
         Case 4
            Return MachineButton4
         Case 5
            Return MachineButton5
         Case 6
            Return MachineButton6
         Case 7
            Return MachineButton7
         Case 8
            Return MachineButton8
         Case 9
            Return MachineButton9
         Case 10
            Return MachineButton10
         Case Else
            Return MachineButton11
      End Select
   End Function

   Private Function GetToggleButtonIndex(ByVal nBtnName As Primitives.ToggleButton) As Integer
      Select Case nBtnName.Name
         Case MachineButton1.Name
            Return 1
         Case MachineButton2.Name
            Return 2
         Case MachineButton3.Name
            Return 3
         Case MachineButton4.Name
            Return 4
         Case MachineButton5.Name
            Return 5
         Case MachineButton6.Name
            Return 6
         Case MachineButton7.Name
            Return 7
         Case MachineButton8.Name
            Return 8
         Case MachineButton9.Name
            Return 9
         Case MachineButton10.Name
            Return 10
         Case Else
            Return 11
      End Select
   End Function

   Private Function GetImage(ByVal nInd As Integer) As Image
      Select Case nInd
         Case 1
            Return ImageButton1
         Case 2
            Return ImageButton2
         Case 3
            Return ImageButton3
         Case 4
            Return ImageButton4
         Case 5
            Return ImageButton5
         Case 6
            Return ImageButton6
         Case 7
            Return ImageButton7
         Case 8
            Return ImageButton8
         Case 9
            Return ImageButton9
         Case 10
            Return ImageButton10
         Case Else
            Return ImageButton11
      End Select
   End Function

   Public Function GetPrivateProfileMachineButtons(
                            ByVal lpAppName As String,
                            ByVal lpKeyName As String,
                            ByRef lpButtonImage As String,
                            ByRef lpCommand As String,
                            ByRef lpStateFlag As String,
                            ByVal lpFileName As String) As Boolean

      Dim sVal As String = String.Empty
      GetPrivateProfileString(lpAppName, lpKeyName, "", sVal, lpFileName)
      Dim sItems() As String = sVal.Split(",".ToCharArray)
      If sItems.Count() >= 2 Then
         lpButtonImage = sItems(0)
         lpCommand = sItems(1)
         If sItems.Count() >= 3 Then
            lpStateFlag = sItems(2)
         Else
            lpStateFlag = BTN_STATE_NOTHING
         End If
         Return True
      End If
      Return False

   End Function

End Class
