Imports System.Collections.ObjectModel
Imports EgtUILib

Public Class ChangeToolWD
   Private m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)

   Private m_SetUpMachiningList As New ObservableCollection(Of ItemMachining)

   Sub New(Owner As Window)
      Me.Owner = Owner
      InitializeComponent()
   End Sub

   ' Parametri della lama impostata correntemente in macchina
   Private m_DefaultSaw_Name As String = String.Empty
   Private m_DefaultSaw_Diam As Double = 0
   Private m_DefaultSaw_Thick As Double = 0
   Private m_DefaultSaw_Exists As Boolean = False

   ' Il nome della lavorazione restituito dalla selezione
   Private m_NewSawing As String = String.Empty
   Public ReadOnly Property NewSawing As String
      Get
         Return m_NewSawing
      End Get
   End Property

   ' Il colore della lavorazione
   Private m_EgtColor As New Color3d
   Public ReadOnly Property EgtColor As Color3d
      Get
         Return m_EgtColor
      End Get
   End Property

   ' Il nome della posizione sulla rulliera
   Private m_TCPos As String = String.Empty
   Public ReadOnly Property TCPos As String
      Get
         Return m_TCPos
      End Get
   End Property

   ' Nome della lavorazione corrente
   Private m_CurrSawing As String = String.Empty
   Public Property CurrSawing As String
      Get
         Return m_CurrSawing
      End Get
      Set(value As String)
         m_CurrSawing = value
      End Set
   End Property

   Private Sub GetDiamAndThickDefaultSaw()
      m_DefaultSaw_Name = m_MainWindow.m_CurrentMachine.sCurrSaw
      ' Dalla lavorazione corrente recupero il nome della lama
      If EgtMdbSetCurrMachining(m_CurrSawing) Then
         Dim sNameTool As String = String.Empty
         If EgtMdbGetCurrMachiningParam(MCH_MP.TOOL, sNameTool) Then m_DefaultSaw_Name = sNameTool
      End If
      If EgtTdbSetCurrTool(m_DefaultSaw_Name) Then
         ' Diametro lama lavorazione
         EgtTdbGetCurrToolParam(MCH_TP.DIAM, m_DefaultSaw_Diam)
         ' Spessore lama corrente
         EgtTdbGetCurrToolParam(MCH_TP.THICK, m_DefaultSaw_Thick)
         m_DefaultSaw_Exists = True
      End If
   End Sub

   Private Sub OpenFile_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
      ' Posizione finestra
      Me.Top = Owner.Top + Owner.Height / 2 - Me.Height / 2
      Me.Left = Owner.Left + Owner.Width / 2 - Me.Width / 2
      ' Definizione del collegamento tra ItemList e ListBox1
      SetUpToolListBox.ItemsSource = m_SetUpMachiningList
      ' 90378=Seleziona lavorazione
      FilePathTxBl.Text = EgtMsg(90378)
   End Sub

   Private Sub OpenFile_Loaded(sender As Object, e As EventArgs) Handles Me.Loaded
      If String.IsNullOrEmpty(m_CurrSawing) Then
         m_CurrSawing = m_MainWindow.m_CurrentMachine.sCurrSawing
      End If
      ' carico elenco degli utensili impostati attualmente in macchina (anche il laser!)
      LoadSetUpMachining()
      ' ricerco la lavorazione corrente
      Dim Item As ItemMachining = m_SetUpMachiningList.FirstOrDefault(Function(x) x.Machining = m_CurrSawing)
      Dim Index As Integer = m_SetUpMachiningList.IndexOf(Item)
      If Index < 0 Then
         ' Imposto lavorazione di default  
         EgtMdbSetCurrMachining(m_CurrSawing)
         Dim sTool As String = String.Empty
         EgtMdbGetCurrMachiningParam(MCH_MP.TOOL, sTool)
         ' ⚠️ Utensile {0} non attrezzato
         ErrorTxBl.Text = String.Format(EgtMsg(90377), sTool)
         Index = 0
      End If
      ' se presente seleziono il primo elemento
      If m_SetUpMachiningList.Count > 0 Then
         SetUpToolListBox.SelectedItem = m_SetUpMachiningList(Index)
         OkBtn.IsEnabled = True
      Else
         OkBtn.IsEnabled = False
      End If
   End Sub

#Region "SET UP MACHINING"

   ' Creo le liste da mostrare nella lista
   Private Function LoadSetUpMachining() As Boolean
      Dim sNameTool As String = String.Empty
      Dim nType As Integer = 0
      Dim sHeadTool As String = String.Empty
      Dim nExitTool As Integer = 0
      ' Imposto il contesto corrente
      EgtSetCurrentContext(m_MainWindow.m_CurrentProjectPageUC.CurrentProjectScene.GetCtx())
      ' Recupero la lista di tutte le lavorazioni di lama
      Dim local_Sawing As TreeViewItem.CathegoryItem = GetAllSwaing()
      ' Se non ci sono lavorazioni di lama allora esco
      If IsNothing(local_Sawing) Then Return False

      ' Ripulisco la lista degli utensili
      m_SetUpMachiningList.Clear()
      CreateSawingList(local_Sawing)

      Return True
   End Function

   ' Creo la lista delle delle lavorazioni di lama da proporre
   Private Sub CreateSawingList(SawingFam As TreeViewItem.CathegoryItem)
      ' Recupero le info della lama montata di default
      GetDiamAndThickDefaultSaw()
      ' recupero la prima lavorazione
      For Each Item As TreeViewItem.CustomItem In SawingFam.Items
         Dim sNameTool As String = String.Empty
         ' Imposto la lavorazione corrente
         EgtMdbSetCurrMachining(Item.Name)
         ' Recupero il nome dell'utensile della lavorazione
         EgtMdbGetCurrMachiningParam(MCH_MP.TOOL, sNameTool)
         If Not String.IsNullOrEmpty(sNameTool) And VerifyCurrSawTollerance(sNameTool) Then
            ' Verifico che sia montata su un portautensile
            EgtTdbSetCurrTool(sNameTool)
            Dim sTCPos As String = String.Empty
            EgtTdbGetCurrToolParam(MCH_TP.TCPOS, sTCPos)
            If Not String.IsNullOrEmpty(sTCPos) Then
               ' Cerco nel porta utensili automaitico 
               For Each ToolPosition As ToolChangerPos In m_MainWindow.m_CurrentMachine.ToolChanger
                  If ToolPosition.sTool <> String.Empty Then
                     If sNameTool = ToolPosition.sTool Then
                        ' Verifico che il materiale e lo spessore
                        If VerifyCurrMachiningMaterial() Then
                           m_SetUpMachiningList.Add(New ItemMachining(Item.Name, sNameTool, sTCPos, Utility.GetColorPV()))
                        End If
                        Exit For
                     End If
                  End If
               Next
            End If
         End If
      Next
      ' reimposto la lavorazione di lama e la lama impostate in macchina
      EgtTdbSetCurrTool(m_MainWindow.m_CurrentMachine.sCurrSaw)
      EgtMdbSetCurrMachining(m_MainWindow.m_CurrentMachine.sCurrSawing)
   End Sub

   ' verifico l'utensile corrente (impostato nella funzione chiamante) se può lavorare il grezzo corrente
   Private Function VerifyCurrMachiningMaterial() As Boolean
      Dim m_MaterialsList As New ObservableCollection(Of MachiningMaterial)
      For Each Material As Material In m_MainWindow.m_CurrentMachine.Materials
         If m_MainWindow.m_CurrentMachine.bWaterJet And m_MainWindow.m_CurrentMachine.bFromDBWaterJet Then
            m_MaterialsList.Add(New MachiningMaterial(Material.nId, Material.sName, Material.SubId))
         Else
            m_MaterialsList.Add(New MachiningMaterial(Material.nId, Material.sName))
         End If
      Next

      Dim ToolString As String = String.Empty
      EgtMdbGetCurrMachiningParam(MCH_MP.SYSNOTES, ToolString)
      If ToolString <> String.Empty Then
         Dim sItems() = ToolString.Split(";".ToCharArray)
         Dim Index As Integer = 0
         For Each Material As MachiningMaterial In m_MaterialsList
            Dim Param() As String = sItems(Index).Split(",".ToCharArray)
            Dim SubParam() As String = Param(0).Split(".".ToCharArray)
            Dim nParId As Integer = 0
            Dim nSubParId As Integer = 0
            If m_MainWindow.m_CurrentMachine.bWaterJet And m_MainWindow.m_CurrentMachine.bFromDBWaterJet Then
               If StringToInt(SubParam(0), nParId) AndAlso nParId = m_MainWindow.m_CurrentMachine.CurrMat.nId AndAlso SubParam.Count > 1 AndAlso
                  StringToInt(SubParam(1), nSubParId) AndAlso nSubParId = Material.nSubId Then
                  StringToDouble(Param(1), Material.dMinThickness)
                  StringToDouble(Param(2), Material.dMaxThickness)
                  Material.VerifyIfActive()
               Else
                  Material.VerifyIfActive()
               End If
            Else
               If StringToInt(Param(0), nParId) AndAlso nParId = m_MainWindow.m_CurrentMachine.CurrMat.nId Then
                  StringToDouble(Param(1), Material.dMinThickness)
                  StringToDouble(Param(2), Material.dMaxThickness)
                  Material.VerifyIfActive()
                  If m_MainWindow.m_CurrentProjectPageUC.m_dRawHeight > Material.dMinThickness And m_MainWindow.m_CurrentProjectPageUC.m_dRawHeight < Material.dMaxThickness Then
                     Return True
                  End If
               End If
            End If
            Index += 1
         Next
      End If
      Return False
   End Function

   ' verifico l'utensile corrente (impostato nella funzione chiamante) se ha le stesse dimensioni della lama di default
   Private Function VerifyCurrSawTollerance(sNameTool As String) As Boolean
      If m_DefaultSaw_Exists Then
         If EgtTdbSetCurrTool(sNameTool) Then
            ' Diametro nuova lama
            Dim NewDiam As Double = 0
            EgtTdbGetCurrToolParam(MCH_TP.DIAM, NewDiam)
            ' Spessore lama
            Dim NewThick As Double = 0
            EgtTdbGetCurrToolParam(MCH_TP.THICK, NewThick)
            ' Verifico che la nuova lama possa essere applicata: diametro minore, uguale spessore
            Dim Delta_Diam As Double = NewDiam - m_DefaultSaw_Diam
            Dim Delta_Thick As Double = Math.Abs(NewThick - m_DefaultSaw_Thick)
            If Delta_Diam < EPS_SMALL And Delta_Thick < EPS_SMALL Then
               Return True
            Else
               EgtOutLog(String.Format("New saw {0} can not repalce the current {1}; Delta_Diam={2}, |Delta_Thick|={3} ", sNameTool, m_DefaultSaw_Name, Delta_Diam, Delta_Thick))
            End If
         Else
            EgtOutLog("Impossible to find in tooldb SAW: " & sNameTool)
         End If
      Else
         If String.IsNullOrEmpty(m_DefaultSaw_Name) Then
            EgtOutLog("There is no currsaw setted in machine!")
         Else
            EgtOutLog("Impossible to find in tooldb currsaw setted in machine: " & m_DefaultSaw_Name)
         End If
      End If
      Return False
   End Function

   ' Restituisce tutto l'elenco delle lavorazioni disponibili in macchina
   Private Function GetAllSwaing() As TreeViewItem.CathegoryItem
      Dim sFName As String = EgtMsg(90771)   ' Uscita
      Dim nFType As Integer = MCH_MY.SAWING
      If Not m_MainWindow.m_CurrentMachine.bSawing Then Return Nothing
      ' Inserisco categoria ed eventuali elementi
      Dim MachiningCathegory As New TreeViewItem.CathegoryItem(sFName, nFType)
      Dim MachiningName As String = String.Empty
      If EgtMdbGetFirstMachining(nFType, MachiningName) Then
         MachiningCathegory.Items.Add(New TreeViewItem.CustomItem(MachiningName, nFType))
         While EgtMdbGetNextMachining(nFType, MachiningName)
            MachiningCathegory.Items.Add(New TreeViewItem.CustomItem(MachiningName, nFType))
         End While
      End If
      Return MachiningCathegory
   End Function

#End Region    ' Set up machinining

   Private Sub SetUpToolListBox_PreviewMouseUp(sender As Object, e As MouseButtonEventArgs) Handles SetUpToolListBox.PreviewMouseUp
      ' Disabilito Ok
      OkBtn.IsEnabled = False
      ' Recupero item selezionato
      If SetUpToolListBox.SelectedItems.Count() = 0 Then
         Return
      End If
      m_NewSawing = m_SetUpMachiningList(SetUpToolListBox.SelectedIndex).Machining
      m_EgtColor = m_SetUpMachiningList(SetUpToolListBox.SelectedIndex).PrintFootToolColor
      m_TCPos = m_SetUpMachiningList(SetUpToolListBox.SelectedIndex).ToolPos
      ' A seconda del tipo
      OkBtn.IsEnabled = True
   End Sub

   Private Sub SetUpToolListBox_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles SetUpToolListBox.SelectionChanged
      ' Disabilito Ok
      OkBtn.IsEnabled = False
      ' Recupero item selezionato
      If SetUpToolListBox.SelectedItems.Count() = 0 Then
         Return
      Else
         m_NewSawing = m_SetUpMachiningList(SetUpToolListBox.SelectedIndex).Machining
         m_EgtColor = m_SetUpMachiningList(SetUpToolListBox.SelectedIndex).PrintFootToolColor
         m_TCPos = m_SetUpMachiningList(SetUpToolListBox.SelectedIndex).ToolPos
         OkBtn.IsEnabled = True
      End If
   End Sub

   Private Sub OkBtn_Click(sender As Object, e As RoutedEventArgs) Handles OkBtn.Click
      DialogResult = True
   End Sub

End Class

Public Class ItemMachining

   Private m_ToolPos As String = String.Empty
   Private m_ToolName As String = String.Empty
   Private m_Machining As String = String.Empty
   Private m_ToolExit As Integer = 1
   Private m_ToolType As Integer = -1
   Private m_PrintFootToolColor As New Color3d(0, 255, 0, 100)
   Private m_cSawColor As SolidColorBrush

   ' Posizione porta utensile
   Public Property ToolPos As String
      Get
         Return m_ToolPos
      End Get
      Set(value As String)
         m_ToolPos = value
      End Set
   End Property

   ' Nome utensile
   Public Property ToolName As String
      Get
         Return m_ToolName
      End Get
      Set(value As String)
         m_ToolName = value
      End Set
   End Property

   ' Nome della lavorazione
   Public Property Machining As String
      Get
         Return m_Machining
      End Get
      Set(value As String)
         m_Machining = value
      End Set
   End Property

   Public Property ToolExit As Integer
      Get
         Return m_ToolExit
      End Get
      Set(value As Integer)
         m_ToolExit = value
      End Set
   End Property

   Public Property ToolType As Integer
      Get
         Return m_ToolType
      End Get
      Set(value As Integer)
         m_ToolType = value
      End Set
   End Property

   Public Property PrintFootToolColor As Color3d
      Get
         Return m_PrintFootToolColor
      End Get
      Set(value As Color3d)
         m_PrintFootToolColor = value
      End Set
   End Property

   Public Property SawColor As SolidColorBrush
      Get
         Return m_cSawColor
      End Get
      Set(value As SolidColorBrush)
         m_cSawColor = value
      End Set
   End Property

   Sub New(sMachining As String, sToolName As String, sToolPos As String, cColor As Color3d)
      m_Machining = sMachining
      m_ToolPos = sToolPos
      m_ToolName = sToolName
      m_PrintFootToolColor = cColor
      m_cSawColor = New SolidColorBrush(Color.FromRgb(m_PrintFootToolColor.R, m_PrintFootToolColor.G, m_PrintFootToolColor.B))
   End Sub

End Class
