Imports EgtUILib

Public Class FastGridSlabManager

   ' Riferimento alla MainWindow
   Private m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)

   ' Flag prima apertura
   Private m_bFirst As Boolean = True
   ' Dati ordine
   Private m_nCurrSlab As Integer = 0
   Private m_nPieceType As Integer = 0
   Private m_PieceDimensionsX(4) As Integer
   Private m_PieceDimensionsY(4) As Integer
   Private m_sCompoDir As String = String.Empty

   ' Costante minima dimensione pezzo
   Private Const MIN_DIM As double = 10

   Private Sub FastGridSlabManager_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
      ' Imposto i messaggi letti dal file dei messaggi
      OrderTxBl.Text = EgtMsg(MSG_FASTGRIDPAGEUC)                    'Order name - Nome ordine
      CurrSlabTxBl.Text = EgtMsg(MSG_FASTGRIDPAGEUC + 1)             'Curr slab - Lastra corrente
      PieceTypeGpBx.Header = EgtMsg(MSG_FASTGRIDPAGEUC + 3)          'Piece type - Tipo pezzo
      ConfirmOrderBtn.Content = EgtMsg(MSG_FASTGRIDPAGEUC + 5)       'Confirm order - Conferma ordine
      InsertPiecesBtn.Content = EgtMsg(MSG_FASTGRIDPAGEUC + 4)       'Insert pieces - Inserisci pezzi
      LastSlabBtn.Content = EgtMsg(MSG_FASTGRIDPAGEUC + 2)           'Last slab - Ultima lastra
      ' Leggo dati da ini
      GetPrivateProfileString(S_FASTGRID, K_FG_ORDER, "", OrderTxBx.Text, m_MainWindow.GetIniFile())
      m_nCurrSlab = GetPrivateProfileInt(S_FASTGRID, K_FG_CURRSLAB, 0, m_MainWindow.GetIniFile())
      m_nPieceType = GetPrivateProfileInt(S_FASTGRID, K_FG_PIECETYPE, 0, m_MainWindow.GetIniFile())
   End Sub

   Private Sub FastGridSlabManager_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
      ' Se prima esecuzione
      If m_bFirst Then
         ' Leggo direttorio componenti
         GetPrivateProfileString(S_COMPO, K_COMPODIR, "", m_sCompoDir, m_MainWindow.GetIniFile())
         m_bFirst = False
      End If
      ' Recupero parametri per nesting
      m_MainWindow.m_CadCutPageUC.m_NestPage.LoadParams()
      ' Recupero dimensioni pezzi da ini
      For Index As Integer = 1 To 5
         GetPieceDimensions(Index)
      Next
      ' Ne imposto i valori
      CurrSlabTxBx.Text = m_nCurrSlab
      Type1Btn.IsChecked = False
      Type2Btn.IsChecked = False
      Type3Btn.IsChecked = False
      Type4Btn.IsChecked = False
      Type5Btn.IsChecked = False
      Select Case m_nPieceType
         Case 1
            Type1Btn.IsChecked = True
         Case 2
            Type2Btn.IsChecked = True
         Case 3
            Type3Btn.IsChecked = True
         Case 4
            Type4Btn.IsChecked = True
         Case 5
            Type5Btn.IsChecked = True
      End Select
      ' Verifico se c'e' un ordine in corso
      CurrSlabTxBx.IsEnabled = False
      If m_nCurrSlab > 0 Then
         OrderTxBx.IsEnabled = False
         PieceTypeGpBx.IsEnabled = False
         ConfirmOrderBtn.IsEnabled = False
         InsertPiecesBtn.IsEnabled = True
         LastSlabBtn.IsEnabled = True
      Else
         OrderTxBx.IsEnabled = True
         PieceTypeGpBx.IsEnabled = True
         ConfirmOrderBtn.IsEnabled = True
         InsertPiecesBtn.IsEnabled = False
         LastSlabBtn.IsEnabled = False
      End If
      ' Verifico se ultima lastra
      If m_MainWindow.m_CurrentProjectPageUC.GetLastSlab() Then
         LastSlabBtn.IsChecked = True
      End If
      EgtZoom(ZM.ALL)
   End Sub

   Private Sub InsertPiecesBtn_Click(sender As Object, e As RoutedEventArgs) Handles InsertPiecesBtn.Click
      m_MainWindow.m_CurrentProjectPageUC.SetProjectOrder(OrderTxBx.Text)
      ' Rimuovo tutti i pezzi
      RemoveAllParts()
      ' Lancio l'inserimento dei pezzi
      ExecInsert()
      ' Aggiorno visualizzazione
      EgtZoom(ZM.ALL)
   End Sub

   Private Sub LastSlabBtn_Click(sender As Object, e As RoutedEventArgs) Handles LastSlabBtn.Click
      If LastSlabBtn.IsChecked Then
         m_MainWindow.m_CurrentProjectPageUC.SetLastSlab()
      Else
         m_MainWindow.m_CurrentProjectPageUC.ResetLastSlab()
      End If
   End Sub

   Friend Sub RemoveAllParts()
      Dim nRawId As Integer = CamAuto.GetCurrentRaw()
      Dim nPartId As Integer = EgtGetFirstPartInRawPart( nRawId)
      While nPartId <> GDB_ID.NULL
         Dim nNextPartId = EgtGetNextPartInRawPart( nPartId)
         ' Rimuovo dal grezzo
         EgtRemovePartFromRawPart(nPartId)
         ' Rimuovo le lavorazioni
         EraseMachinings(nPartId)
         'Cancello
         EgtErase(nPartId)
         ' Passo al successivo
         nPartId = nNextPartId
      End While
   End Sub

   Private Function ExecInsert() As Boolean
      ' Recupero le dimensioni dei pezzi
      Dim dDimX As Double = m_PieceDimensionsX( m_nPieceType - 1)
      Dim dDimY As Double = m_PieceDimensionsY( m_nPieceType - 1)
      ' Imposto la griglia di inserimento
      Dim MyGrid As New InsertGrid
      If Not MyGrid.Init( m_MainWindow, dDimX, dDimY) Then Return False
      ' Abilito regioni per nesting
      m_MainWindow.m_CadCutPageUC.m_NestPage.UpdateNestRegions()
      m_MainWindow.m_CadCutPageUC.m_NestPage.EnableReferenceRegion(false)
      ' Carico lua per creare rettangoli
      Dim sLuaPath = m_sCompoDir & "\Rettangolo.lua"
      If Not EgtLuaExecFile(sLuaPath) Then Return False
      ' Inserisco nel gruppo un nuovo componente per ogni pezzo da inserire
      Dim nId As Integer = GDB_ID.NULL
      For i As Integer = 1 To 100
         EgtLuaSetGlobNumVar("CMP.V1", dDimX)
         EgtLuaSetGlobNumVar("CMP.V2", dDimY)
         ' Esecuzione componente
         If Not EgtLuaExecLine("CMP_Draw(false)") Then Continue For
         ' Recupero Id del nuovo componente
         nId = EgtGetLastPart()
         If nId = GDB_ID.NULL Then Continue For
         ' Muovo la regione in Z per evitare problemi in visualizzazione
         Dim nRegId = EgtGetFirstNameInGroup(nId, NAME_REGION)
         EgtMove(nRegId, New Vector3d(0, 0, DELTAZ_REG), GDB_RT.GLOB)
         ' Aggiusto per lavorazioni
         EgtAdjustFlatPart(nId)
         ' Imposto colore testi
         Utility.SetTextColor( nRegId)
         ' Se primo pezzo, lo inserisco con metodo standard
         If i = 1 Then
            Dim ptGridOrig As Point3d
            If m_MainWindow.m_CadCutPageUC.m_NestPage.InsertOnePart(nId) AndAlso GetPartCenter(nId, ptGridOrig) Then
               MyGrid.SetOrig( ptGridOrig)
               m_MainWindow.m_CadCutPageUC.m_NestPage.EnableReferenceRegion(false)
            Else
               Exit For
            End If
         ' altrimenti lo inserisco nei punti griglia
         Else
            ' Preparo il pezzo per l'inserimento
            If Not m_MainWindow.m_CadCutPageUC.m_NestPage.PreInsertOnePart( nId) Then Exit For
            Dim ptCurr As Point3d
            If Not GetPartCenter( nId, ptCurr) Then Exit For
            ' Cerco la prossima posizione griglia valida
            While True
               ' Cerco il prossimo centro di inserimento
               Dim ptCen As Point3d
               If Not MyGrid.GetNextPoint(ptCen) Then Exit For
               ' Lo sposto nel punto griglia e lo verifico
               Dim vtMove As Vector3d = ptCen - ptCurr
               vtMove.z = 0
               EgtMove( nId, vtMove, GDB_RT.GLOB)
               ptCurr = ptCurr + vtMove
               ' Eseguo verifica
               If EgtVerifyPart(nId, True) Then Exit While
            End While
         End If
      Next
      ' Cancello l'ultimo pezzo che sicuramente non è stato inserito
      m_MainWindow.m_CadCutPageUC.m_NestPage.PreRemoveOnePart( nId)
      EgtErase(nId)
      ' Pulisco lua
      EgtLuaResetGlobVar("CMP")
      EgtLuaResetGlobVar("CMP_Draw")
      Return True
   End Function

   Private Function GetPartCenter( nId As integer, ByRef ptCen As Point3d) As Boolean
      Dim nOutLoopId As Integer = EgtGetFirstNameInGroup( nId, NAME_OUTLOOP)
      Dim b3Part As New BBox3d
      If Not EgtGetBBoxGlob( nOutLoopId, GDB_BB.IGNORE_DIM + GDB_BB.IGNORE_TEXT, b3Part) Then Return false
      ptCen = b3Part.Center()
      Return True
   End Function

   Friend Sub OnPreNewProject()
      ' Se modalità FastGrid attiva e abilitata
      If GetPrivateProfileInt(S_FASTGRID, K_FG_ENABLE, 0, m_MainWindow.GetIniFile()) <> 0 And
         GetPrivateProfileInt(S_FASTGRID, K_FG_ACTIVE, 0, m_MainWindow.GetIniFile()) <> 0 Then
         ' Se il progetto precedente è stato inviato alla macchina
         If m_MainWindow.m_CurrentProjectPageUC.GetProjectNcProgSent() <> 0 Then
            CurrSlabIncrement()
         End If
      End If
   End Sub

   Friend Sub OnPostNewProject()
      ' Se modalità FastGrid attiva e abilitata
      If GetPrivateProfileInt(S_FASTGRID, K_FG_ENABLE, 0, m_MainWindow.GetIniFile()) <> 0 And
         GetPrivateProfileInt(S_FASTGRID, K_FG_ACTIVE, 0, m_MainWindow.GetIniFile()) <> 0 Then
         If LastSlabBtn.IsChecked Then
            m_MainWindow.m_CurrentProjectPageUC.SetLastSlab()
         Else
            m_MainWindow.m_CurrentProjectPageUC.ResetLastSlab()
         End If
         m_MainWindow.m_CurrentProjectPageUC.SaveProject()
      End If
   End Sub

   Private Sub OrderTxBx_EgtClosed(sender As Object, e As EventArgs) Handles OrderTxBx.EgtClosed
      WritePrivateProfileString(S_FASTGRID, K_FG_ORDER, OrderTxBx.Text, m_MainWindow.GetIniFile())
   End Sub

   Private Sub PiecesTypeBtn_Click(sender As Object, e As RoutedEventArgs) Handles Type1Btn.Click, Type2Btn.Click, Type3Btn.Click, Type4Btn.Click, Type5Btn.Click
      If sender Is Type1Btn Then
         m_nPieceType = 1
         Type1Btn.IsChecked = True
         Type2Btn.IsChecked = False
         Type3Btn.IsChecked = False
         Type4Btn.IsChecked = False
         Type5Btn.IsChecked = False
      ElseIf sender Is Type2Btn Then
         m_nPieceType = 2
         Type1Btn.IsChecked = False
         Type2Btn.IsChecked = True
         Type3Btn.IsChecked = False
         Type4Btn.IsChecked = False
         Type5Btn.IsChecked = False
      ElseIf sender Is Type3Btn Then
         m_nPieceType = 3
         Type1Btn.IsChecked = False
         Type2Btn.IsChecked = False
         Type3Btn.IsChecked = True
         Type4Btn.IsChecked = False
         Type5Btn.IsChecked = False
      ElseIf sender Is Type4Btn Then
         m_nPieceType = 4
         Type1Btn.IsChecked = False
         Type2Btn.IsChecked = False
         Type3Btn.IsChecked = False
         Type4Btn.IsChecked = True
         Type5Btn.IsChecked = False
      ElseIf sender Is Type5Btn Then
         m_nPieceType = 5
         Type1Btn.IsChecked = False
         Type2Btn.IsChecked = False
         Type3Btn.IsChecked = False
         Type4Btn.IsChecked = False
         Type5Btn.IsChecked = True
      Else
         Return
      End If
      WritePrivateProfileString(S_FASTGRID, K_FG_PIECETYPE, m_nPieceType, m_MainWindow.GetIniFile())
   End Sub

   Private Sub ConfirmOrderBtn_Click(sender As Object, e As RoutedEventArgs) Handles ConfirmOrderBtn.Click
      If Not String.IsNullOrEmpty(OrderTxBx.Text) And m_nPieceType > 0 And m_nPieceType <= 5 Then
         m_nCurrSlab = 1
         CurrSlabTxBx.Text = 1
         WritePrivateProfileString(S_FASTGRID, K_FG_CURRSLAB, m_nCurrSlab, m_MainWindow.GetIniFile())
         OrderTxBx.IsEnabled = False
         PieceTypeGpBx.IsEnabled = False
         ConfirmOrderBtn.IsEnabled = False
         InsertPiecesBtn.IsEnabled = True
         LastSlabBtn.IsEnabled = True
      Else
         ' segnalare che i dati ordine non sono accettabili

      End If
   End Sub

   Private Sub GetPieceDimensions(Index As Integer)
      Dim DimensionString As String = ""
      GetPrivateProfileString(S_FASTGRID, Index, "", DimensionString, m_MainWindow.GetIniFile())
      Dim DimensionSplit() As String = DimensionString.Split(","c)
      If DimensionSplit.Count = 3 Then
         m_PieceDimensionsX(Index - 1) = DimensionSplit(0)
         m_PieceDimensionsY(Index - 1) = DimensionSplit(1)
         Select Case Index
            Case 1
               Type1Btn.Content = DimensionSplit(2)
            Case 2
               Type2Btn.Content = DimensionSplit(2)
            Case 3
               Type3Btn.Content = DimensionSplit(2)
            Case 4
               Type4Btn.Content = DimensionSplit(2)
            Case 5
               Type5Btn.Content = DimensionSplit(2)
         End Select
      End If
   End Sub

   Friend Sub CurrSlabIncrement()
      ' Se ultima lastra
      If m_MainWindow.m_CurrentProjectPageUC.GetLastSlab() Then
         ' L'ordine è finito
         m_nCurrSlab = 0
         WritePrivateProfileString(S_FASTGRID, K_FG_CURRSLAB, m_nCurrSlab, m_MainWindow.GetIniFile())
         OrderTxBx.Text = ""
         OrderTxBx.IsEnabled = True
         PieceTypeGpBx.IsEnabled = True
         ConfirmOrderBtn.IsEnabled = True
         InsertPiecesBtn.IsEnabled = False
         LastSlabBtn.IsEnabled = False
         LastSlabBtn.IsChecked = False
      Else
         ' Incremento il contatore lastra
         m_nCurrSlab += 1
         WritePrivateProfileString(S_FASTGRID, K_FG_CURRSLAB, m_nCurrSlab, m_MainWindow.GetIniFile())
      End If
      CurrSlabTxBx.Text = m_nCurrSlab
   End Sub

   Private Class InsertGrid
      Private m_b3Raw As New BBox3d
      Private m_dStepX As Double
      Private m_dStepY As Double
      Private m_ptGridOrig As Point3d
      Private m_nStartX As Integer
      Private m_nStepX As Integer
      Private m_nStepY As Integer

      Friend Function Init(MainWnd As MainWindow, dDimX As Double, dDimY As Double) As Boolean
         ' Box del grezzo
         If Not CamAuto.GetRawBox(m_b3Raw) Then Return False
         ' Spessore della lama corrente
         Dim dSawThick As Double
         If not EgtTdbSetCurrTool(MainWnd.m_CurrentMachine.sCurrSaw) OrElse
            not EgtTdbGetCurrToolParam(MCH_TP.THICK, dSawThick) Then Return false
         ' Determino i passi di griglia
         If dDimX < MIN_DIM Or dDimY < MIN_DIM Then Return False
         m_dStepX = dDimX + dSawThick
         m_dStepY = dDimY + dSawThick
         ' Imposto la posizione iniziale
         m_nStartX = 0
         m_nStepX = 0
         m_nStepY = 0
         Return True
      End Function

      Friend Sub SetOrig( ptOrig As Point3d)
         m_ptGridOrig = ptOrig
         m_nStartX = ( m_b3Raw.Min().x + 0.5 * m_dStepX - ptOrig.x) / m_dStepX
         m_nStepX = 0
         m_nStepY = ( m_b3Raw.Min().y + 0.5 * m_dStepY - ptOrig.y) / m_dStepY
      End Sub

      Friend Function GetNextPoint( ByRef ptCen As Point3d) As Boolean
         ' Mi muovo sulla riga
         m_nStepX += 1
         ptCen = m_ptGridOrig + m_nStepX * m_dStepX * Vector3d.X_AX() + m_nStepY * m_dStepY * Vector3d.Y_AX()
         If m_b3Raw.EnclosesXY( ptCen) Then Return True
         ' Vada alla riga successiva
         m_nStepY += 1
         m_nStepX = m_nStartX
         ptCen = m_ptGridOrig + m_nStepX * m_dStepX * Vector3d.X_AX() + m_nStepY * m_dStepY * Vector3d.Y_AX()
         Return m_b3Raw.EnclosesXY( ptCen)
      End Function

   End Class

End Class
