Imports System.IO
Imports System.Windows.Threading
Imports EgtUILib

Public Class ManualAxesMoveUC

   ' Dichiarazione delle Page UserControl
   Private m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
   Friend m_CN As CN_generico

   ' Modalità di movimento (G0 o G1)
   Private m_bG0Active As Boolean

   ' Timer per aggiornamento nomi assi
   Private m_Timer As New DispatcherTimer

   Private Sub ManualAxesMove_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
      ' Nomi feed e speed
      FeedTxBl.Text = "F"
      SpeedTxBl.Text = "S"
      ' Messaggi
      L1SawThChBx.Content = EgtMsg(90232)   ' Spessore lama
      L2SawThChBx.Content = EgtMsg(90232)   ' Spessore lama
      AddHandler m_Timer.Tick, AddressOf Timer_tick
   End Sub

   Private Sub ManualAxesMove_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
      ' Valori feed e speed da lama corrente
      Dim dTemp As Double = 0
      EgtTdbSetCurrTool(m_MainWindow.m_CurrentProjectPageUC.ToolTxBx.Text)
      EgtTdbGetCurrToolParam(MCH_TP.FEED, dTemp)
      FeedTxBx.Text = LenToString(dTemp, 2)
      EgtTdbGetCurrToolParam(MCH_TP.SPEED, dTemp)
      SpeedTxBx.Text = DoubleToString(dTemp, 0)
      ' Nomi assi
      UpdateAxesNames()
      ' Valori assi lineari : assegno '0' perchè incrementali
      L1TxBx.Text = "0"
      L2TxBx.Text = "0"
      L3TxBx.Text = "0"
      ' Valori assi rotanti : assegno i valori macchina
      Dim dL1, dL2, dL3, dR1, dR2 As Double
      m_MainWindow.m_CNCommunication.GetAxesPositions(dL1, dL2, dL3, dR1, dR2)
      R1TxBx.Text = DoubleToString(dR1, 3)
      R2TxBx.Text = DoubleToString(dR2, 3)
      ' Lancio timer per aggiornamento interfaccia
      m_Timer.Interval = TimeSpan.FromMilliseconds(200)
      m_Timer.Start()
      ' Imposto movimenti in rapido
      G0Btn.IsChecked = True
      ' Imposto check per considerare spessore lama
      L1SawThChBx.IsChecked = m_MainWindow.m_CurrentMachine.bAddSawThTo5AxMove
      L2SawThChBx.IsChecked = m_MainWindow.m_CurrentMachine.bAddSawThTo5AxMove
   End Sub

   Private Sub ManualAxesMove_UnLoaded(sender As Object, e As RoutedEventArgs) Handles Me.Unloaded
      m_Timer.Stop()
      m_MainWindow.m_CurrentMachine.bAddSawThTo5AxMove = (L1SawThChBx.IsEnabled And L1SawThChBx.IsChecked) Or
                                                         (L2SawThChBx.IsEnabled And L2SawThChBx.IsChecked)
   End Sub

   Private Sub UpdateAxesNames()
      Dim sL1 As String = String.Empty
      Dim sL2 As String = String.Empty
      Dim sL3 As String = String.Empty
      Dim sR1 As String = String.Empty
      Dim sR2 As String = String.Empty
      m_MainWindow.m_CNCommunication.GetAxesNames(sL1, sL2, sL3, sR1, sR2)
      Dim b5AxisOn As Boolean = False
      If m_MainWindow.m_CNCommunication.m_nNCType = 3 AndAlso m_MainWindow.m_CNCommunication.m_CN.m_IsSiemensOne Then
         b5AxisOn = m_CN.b5AxesState
      Else
         b5AxisOn = m_CN.Is_G24_active()
      End If
      If Not b5AxisOn Then
         L1Btn.Content = sL1        ' X
         L2Btn.Content = sL2        ' Y
         L3Btn.Content = sL3        ' Z
      Else
         L1Btn.Content = "P"        ' perpendicular
         L2Btn.Content = "H"        ' horizontal
         L3Btn.Content = "V"        ' vertical
      End If
      R1Btn.Content = sR1           ' C
      R2Btn.Content = sR2           ' B
   End Sub

   Private Sub UpdateUseSawThickness()
      Dim b5AxisOn As Boolean = False
      If m_MainWindow.m_CNCommunication.m_nNCType = 3 AndAlso m_MainWindow.m_CNCommunication.m_CN.m_IsSiemensOne Then
         b5AxisOn = m_CN.b5AxesState
      Else
         b5AxisOn = m_CN.Is_G24_active()
      End If
      If Not b5AxisOn Then
         ' Recupero la posizione macchina
         Dim dL1, dL2, dL3, dR1, dR2 As Double
         If Not m_MainWindow.m_CNCommunication.GetAxesPositions(dL1, dL2, dL3, dR1, dR2) Then
            L1SawThChBx.IsEnabled = False
            L2SawThChBx.IsEnabled = False
            Return
         End If
         ' Abilito flag X se lama diretta lungo Y
         If Math.Abs(dR1) < 10 * EPS_ANG_SMALL Or
            Math.Abs(dR1 - 180) < 10 * EPS_ANG_SMALL Or
            Math.Abs(dR1 + 180) < 10 * EPS_ANG_SMALL Then
            L1SawThChBx.IsEnabled = True
            L2SawThChBx.IsEnabled = False
         ElseIf Math.Abs(dR1 - 90) < 10 * EPS_ANG_SMALL Or
                Math.Abs(dR1 + 90) < 10 * EPS_ANG_SMALL Then
            L1SawThChBx.IsEnabled = False
            L2SawThChBx.IsEnabled = True
         Else
            L1SawThChBx.IsEnabled = False
            L2SawThChBx.IsEnabled = False
         End If
      Else
         L1SawThChBx.IsEnabled = m_MainWindow.m_CurrentMachine.bAddSawThTo5AxMove
         L2SawThChBx.IsEnabled = False
      End If
   End Sub

   Private Sub Timer_tick()
      UpdateAxesNames()
      UpdateUseSawThickness()
   End Sub

   Private m_MoveClicked As Boolean = False
   Private Sub XXBtn_Click(sender As Object, e As MouseButtonEventArgs) Handles L1Btn.PreviewMouseDown, L2Btn.PreviewMouseDown, L3Btn.PreviewMouseDown, R1Btn.PreviewMouseDown, R2Btn.PreviewMouseDown
      If e.ClickCount > 1 OrElse m_MoveClicked Then
         Return
      End If
      m_MoveClicked = True
      Dim CurrentBtn As Button = DirectCast(e.Source, Button)
      If m_MainWindow.m_CNCommunication.m_nNCType = 3 AndAlso m_MainWindow.m_CNCommunication.m_CN.m_IsSiemensOne Then
         SiemensMoveAxis(CurrentBtn)
         m_MoveClicked = False
         Return
      End If
      Dim nTemp As Integer = 0
      Dim dTemp As Double = 0
      Dim CmdString As String = String.Empty
      EgtLuaExecFile(m_MainWindow.m_CurrentMachine.sMachDir() & "\DirectCmd\AxesMove.lua")
      EgtLuaSetGlobBoolVar("CMD.G0", m_bG0Active)
      StringToLen(FeedTxBx.Text, dTemp)
      EgtLuaSetGlobNumVar("CMD.F", dTemp)
      StringToDouble(SpeedTxBx.Text, dTemp)
      EgtLuaSetGlobNumVar("CMD.S", dTemp)
      ' Leggo gli assi rispetto allo 0 macchina
      m_CN.set_OP_OM(0)
      System.Threading.Thread.Sleep(100)
      Dim dL1o, dL2o, dL3o As Double
      m_MainWindow.m_CNCommunication.GetLinearAxesPositions(dL1o, dL2o, dL3o)
      Dim dR1, dR2 As Double
      m_MainWindow.m_CNCommunication.GetRotaryAxesPositions(dR1, dR2)
      EgtLuaSetGlobNumVar("CMD.L1o", dL1o)
      EgtLuaSetGlobNumVar("CMD.L2o", dL2o)
      EgtLuaSetGlobNumVar("CMD.L3o", dL3o)
      EgtLuaSetGlobNumVar("CMD.R1", dR1)
      EgtLuaSetGlobNumVar("CMD.R2", dR2)
      ' Leggo gli assi lineari rispetto allo 0 pezzo (per essere compatibile con G150)
      m_CN.set_OP_OM(1)
      System.Threading.Thread.Sleep(1000)
      Dim dL1, dL2, dL3 As Double
      m_MainWindow.m_CNCommunication.GetLinearAxesPositions(dL1, dL2, dL3)
      EgtLuaSetGlobNumVar("CMD.L1", dL1)
      EgtLuaSetGlobNumVar("CMD.L2", dL2)
      EgtLuaSetGlobNumVar("CMD.L3", dL3)
      ' Ripristino lettura rispetto a 0 macchina
      m_CN.set_OP_OM(0)
      System.Threading.Thread.Sleep(100)
      ' Leggo se in modalità 3a o 5a
      Dim bG24On As Boolean = m_CN.Is_G24_active()
      EgtLuaSetGlobBoolVar("CMD.G24", bG24On)
      ' Recupero spessore lama corrente
      Dim sSaw As String = m_MainWindow.m_CurrentMachine.sCurrSaw
      EgtTdbSetCurrTool(sSaw)
      Dim dThick As Double = 0
      EgtTdbGetCurrToolParam(MCH_TP.THICK, dThick)
      EgtLuaSetGlobNumVar("CMD.SAWTH", dThick)
      ' Assegno nome e valore asse da muovere
      Dim sAxName As String = GetAxisName(CurrentBtn)
      Dim dAxVal As Double = GetAxisMove(CurrentBtn)
      If (L1SawThChBx.IsEnabled And L1SawThChBx.IsChecked And sAxName = "X") Or
         (L2SawThChBx.IsEnabled And L2SawThChBx.IsChecked And sAxName = "Y") Then
         If dAxVal > 0 Then
            dAxVal += dThick
         ElseIf dAxVal < 0 Then
            dAxVal -= dThick
         End If
      End If
      EgtLuaSetGlobStringVar("CMD.AXISNAME", sAxName)
      EgtLuaSetGlobNumVar("CMD.AXISMOVE", dAxVal)
      ' Calcolo stringa di comando risultante
      EgtLuaCallFunction("CmdString")
      EgtLuaGetGlobStringVar("CMD.CMDSTRING", CmdString)
      ' Reset lua
      EgtLuaResetGlobVar("CmdString")
      EgtLuaResetGlobVar("CMD")
      ' Log del comando
      EgtOutLog("CmdString=" & CmdString)
      ' Eseguo in MDI
      m_CN.DGeneralFunctions_WriteCncMode(2)     ' Modalità MDI
      System.Threading.Thread.Sleep(150)
      m_CN.sz_ManualDataInput = CmdString
      m_CN.MDI_command()
      System.Threading.Thread.Sleep(150)
      m_CN.DGeneralFunctions_CycleStart()
      System.Threading.Thread.Sleep(m_MainWindow.m_CurrentMachine.nThreadSleep)
      m_CN.DGeneralFunctions_WriteCncMode(7)     ' Modalità manuale
      m_MoveClicked = False
   End Sub

   Private Sub SiemensMoveAxis(CurrentBtn As Button)
      ' leggo se stato reset
      If Not m_CN.bResetState Then
         m_MoveClicked = False
         Return
      End If
      ' se in ciclo, esco
      ' calcolo parametri da passare
      Dim nTemp As Integer = 0
      Dim dTemp As Double = 0
      Dim CmdString As String = String.Empty
      EgtLuaExecFile(m_MainWindow.m_CurrentMachine.sMachDir() & "\DirectCmd\AxesMove.lua")
      EgtLuaSetGlobBoolVar("CMD.G0", m_bG0Active)
      StringToLen(FeedTxBx.Text, dTemp)
      EgtLuaSetGlobNumVar("CMD.F", dTemp)
      StringToDouble(SpeedTxBx.Text, dTemp)
      EgtLuaSetGlobNumVar("CMD.S", dTemp)
      ' Leggo gli assi rispetto allo 0 macchina
      m_CN.set_OP_OM(0)
      System.Threading.Thread.Sleep(50)
      Dim dL1o, dL2o, dL3o As Double
      m_MainWindow.m_CNCommunication.GetLinearAxesPositions(dL1o, dL2o, dL3o)
      Dim dR1, dR2 As Double
      m_MainWindow.m_CNCommunication.GetRotaryAxesPositions(dR1, dR2)
      EgtLuaSetGlobNumVar("CMD.L1o", dL1o)
      EgtLuaSetGlobNumVar("CMD.L2o", dL2o)
      EgtLuaSetGlobNumVar("CMD.L3o", dL3o)
      EgtLuaSetGlobNumVar("CMD.R1", dR1)
      EgtLuaSetGlobNumVar("CMD.R2", dR2)
      ' Leggo gli assi lineari rispetto allo 0 pezzo (per essere compatibile con G150)
      m_CN.set_OP_OM(1)
      System.Threading.Thread.Sleep(50)
      Dim dL1, dL2, dL3 As Double
      m_MainWindow.m_CNCommunication.GetLinearAxesPositions(dL1, dL2, dL3)
      EgtLuaSetGlobNumVar("CMD.L1", dL1)
      EgtLuaSetGlobNumVar("CMD.L2", dL2)
      EgtLuaSetGlobNumVar("CMD.L3", dL3)
      ' Ripristino lettura rispetto a 0 macchina
      m_CN.set_OP_OM(0)
      System.Threading.Thread.Sleep(50)
      ' Leggo se in modalità 3a o 5a
      Dim bG24On As Boolean = m_CN.b5AxesState
      EgtLuaSetGlobBoolVar("CMD.G24", bG24On)
      ' Recupero spessore lama corrente
      Dim sSaw As String = m_MainWindow.m_CurrentMachine.sCurrSaw
      EgtTdbSetCurrTool(sSaw)
      Dim dThick As Double = 0
      EgtTdbGetCurrToolParam(MCH_TP.THICK, dThick)
      EgtLuaSetGlobNumVar("CMD.SAWTH", dThick)
      ' Assegno nome e valore asse da muovere
      Dim sAxName As String = GetAxisName(CurrentBtn)
      Dim dAxVal As Double = GetAxisMove(CurrentBtn)
      If (L1SawThChBx.IsEnabled And L1SawThChBx.IsChecked And sAxName = "X") Or
         (L2SawThChBx.IsEnabled And L2SawThChBx.IsChecked And sAxName = "Y") Then
         If dAxVal > 0 Then
            dAxVal += dThick
         ElseIf dAxVal < 0 Then
            dAxVal -= dThick
         End If
      End If
      EgtLuaSetGlobStringVar("CMD.AXISNAME", sAxName)
      EgtLuaSetGlobNumVar("CMD.AXISMOVE", dAxVal)
      ' Calcolo stringa di comando risultante
      EgtLuaCallFunction("CmdString")
      EgtLuaGetGlobStringVar("CMD.CMDSTRING", CmdString)
      ' Reset lua
      EgtLuaResetGlobVar("CmdString")
      EgtLuaResetGlobVar("CMD")
      ' Log del comando
      EgtOutLog("CmdString=" & CmdString)
      ' Creo file 
      Dim sFilePath As String = m_MainWindow.GetCncDir() & "\MANAXMOV.MPF"
      Try
         File.WriteAllLines(sFilePath, New List(Of String)({CmdString, "M30"}), Text.Encoding.UTF8)
      Catch ex As Exception
         EgtOutLog("Eccezione creazione programma: " & ex.Message)
      End Try
      ' Download programma (eventuali errori sono segnalati dalla funzione)
      If m_CN.Download_NC_prog(sFilePath, "MANAXMOV") = 0 Then
         EgtOutLog("Programma caricato")
         System.Threading.Thread.Sleep(150)
         Dim sActivateManAxMov As String = "/plc/OmagCUT_DB.CTRL.Start_Asup"
         ' Attivo variabile per esecuzione comando manuale
         m_CN.DVariables_WriteVariables3(sActivateManAxMov, 1, 1, 0, 0, "")
      End If
   End Sub

   Private Function GetAxisName(ByVal nBtnName As Button) As String
      Dim sL1 As String = String.Empty
      Dim sL2 As String = String.Empty
      Dim sL3 As String = String.Empty
      Dim sR1 As String = String.Empty
      Dim sR2 As String = String.Empty
      m_MainWindow.m_CNCommunication.GetAxesNames(sL1, sL2, sL3, sR1, sR2)
      Select Case nBtnName.Name
         Case L1Btn.Name
            Return sL1
         Case L2Btn.Name
            Return sL2
         Case L3Btn.Name
            Return sL3
         Case R1Btn.Name
            Return sR1
         Case R2Btn.Name
            Return sR2
      End Select
      Return String.Empty
   End Function

   Private Function GetAxisMove(ByVal nBtnName As Button) As Double
      Dim dVal As Double = 0
      Select Case nBtnName.Name
         Case L1Btn.Name
            StringToLen(L1TxBx.Text, dVal)
         Case L2Btn.Name
            StringToLen(L2TxBx.Text, dVal)
         Case L3Btn.Name
            StringToLen(L3TxBx.Text, dVal)
         Case R1Btn.Name
            StringToDouble(R1TxBx.Text, dVal)
         Case R2Btn.Name
            StringToDouble(R2TxBx.Text, dVal)
      End Select
      Return dVal
   End Function

   Private Sub BackBtn_Click(sender As Object, e As RoutedEventArgs) Handles BackBtn.Click
      m_MainWindow.m_DirectCutPageUC.LeftButtonGrid.Children.Remove(Me)
   End Sub

   Private Sub G0Btn_Checked(sender As Object, e As RoutedEventArgs) Handles G0Btn.Checked
      m_bG0Active = True
      G0TxBl.Foreground = Application.Current.FindResource("OmagCut_Blue")
      FeedTxBl.Foreground = Application.Current.FindResource("OmagCut_Gray")
      FeedTxBx.IsEnabled = False
      SpeedTxBl.Foreground = Application.Current.FindResource("OmagCut_Gray")
      SpeedTxBx.IsEnabled = False
   End Sub

   Private Sub G0Btn_Unchecked(sender As Object, e As RoutedEventArgs) Handles G0Btn.Unchecked
      m_bG0Active = False
      G0TxBl.Foreground = Application.Current.FindResource("OmagCut_Gray")
      FeedTxBl.Foreground = Brushes.Black
      FeedTxBx.IsEnabled = True
      SpeedTxBl.Foreground = Brushes.Black
      SpeedTxBx.IsEnabled = True
   End Sub

End Class
