Imports System.Collections.ObjectModel
Imports EgtBEAMWALL.Core
Imports EgtUILib
Imports MigraDoc.DocumentObjectModel
Imports MigraDoc.Rendering

Module Configuration

   ''' <summary>
   ''' trovo ed evidenzio MachGroup e Duplo di questo pezzo
   ''' </summary>
   ''' <param name="nSelBTLPartId">Id pezzo</param>
   Friend Sub SetSearchPiece(nSelBTLPartId As Integer)
      If Not IsNothing(Map.refProjectVM.MachGroupPanelVM) Then
         Dim MachGroupList As New List(Of MyMachGroupVM)
         For Each Machgroup As MyMachGroupVM In Map.refProjectVM.MachGroupPanelVM.MachGroupVMList
            Dim bFound As Boolean = False
            For Each Part As PartVM In Machgroup.PartVMList
               If EgtDuploGetOriginal(Part.nPartId) = nSelBTLPartId Then
                  Part.SetSearchFound()
                  bFound = True
               Else
                  Part.ResetSearchFound()
               End If
            Next
            If bFound Then
               Machgroup.SetSearchFound()
            Else
               Machgroup.ResetSearchFound()
            End If
         Next
      End If
   End Sub

   ''' <summary>
   ''' deevidenzio MachGroup e Duplo di questo pezzo
   ''' </summary>
   ''' <param name="nSelBTLPartId">Id pezzo</param>
   Friend Sub ResetSearchPiece(nSelBTLPartId As Integer)
      If Not IsNothing(Map.refProjectVM.MachGroupPanelVM) Then
         Dim MachGroupList As New List(Of MyMachGroupVM)
         For Each Machgroup As MyMachGroupVM In Map.refProjectVM.MachGroupPanelVM.MachGroupVMList
            Dim bFound As Boolean = False
            For Each Part As PartVM In Machgroup.PartVMList
               If EgtDuploGetOriginal(Part.nPartId) = nSelBTLPartId Then
                  Part.ResetSearchFound()
                  bFound = True
               End If
            Next
            If bFound Then
               Machgroup.ResetSearchFound()
            End If
         Next
      End If
   End Sub

   ''' <summary>
   ''' aggiornamento grafica
   ''' </summary>
   Friend Sub UpdateGraphics()
      If Not IsNothing(Map.refFeatureListManagerVM) Then Map.refFeatureListManagerVM.PartShowAllChanged()
      If Not IsNothing(Map.refBTLPartManagerVM) Then Map.refBTLPartManagerVM.PartShowAllChanged()
   End Sub

   ''' <summary>
   ''' evidenzio BTLPart di questo pezzo
   ''' </summary>
   ''' <param name="nPartId">Id pezzo</param>
   Friend Sub SetSearch(nPartId As Integer)
      For BTLPartIndex = 0 To Map.refProjectVM.BTLStructureVM.BTLPartVMList.Count - 1
         Dim nDuploOriginalId As Integer = 0
         If EgtGetInfo(nPartId, GDB_SI_DUPSOU, nDuploOriginalId) AndAlso nDuploOriginalId > 0 AndAlso nDuploOriginalId = Map.refProjectVM.BTLStructureVM.BTLPartVMList(BTLPartIndex).nPartId Then
            Map.refProjectVM.BTLStructureVM.BTLPartVMList(BTLPartIndex).SetSearchFound()
            Exit For
         End If
      Next
   End Sub

   ''' <summary>
   ''' deevidenzio BTLPart di questo pezzo
   ''' </summary>
   ''' <param name="nPartId">Id pezzo</param>
   Friend Sub ResetSearch(nPartId As Integer)
      For BTLPartIndex = 0 To Map.refProjectVM.BTLStructureVM.BTLPartVMList.Count - 1
         Dim nDuploOriginalId As Integer = 0
         If EgtGetInfo(nPartId, GDB_SI_DUPSOU, nDuploOriginalId) AndAlso nDuploOriginalId > 0 AndAlso nDuploOriginalId = Map.refProjectVM.BTLStructureVM.BTLPartVMList(BTLPartIndex).nPartId Then
            Map.refProjectVM.BTLStructureVM.BTLPartVMList(BTLPartIndex).ResetSearchFound()
            Exit For
         End If
      Next
   End Sub

   ''' <summary>
   ''' modalita' assemblato
   ''' </summary>
   ''' <param name="bShowBuilding">booleano visualizza modalita' assemblato</param>
   Friend Sub AssembledMode(bShowBuilding As Boolean)
      If bShowBuilding AndAlso Map.refShowBeamPanelVM.bShowAll Then
         ' devo smontarlo prima di calcolare le travi, altrimenti non trova i pezzi
         Map.refProjectVM.BTLStructureVM.ShowBuilding(False, False)
      End If
   End Sub

   ''' <summary>
   ''' vista di tutti i pezzi
   ''' </summary>
   ''' <param name="bShowBuilding">booleano visualizza modalita' assemblato</param>
   ''' <param name="bShowSolid">booleano visualizza solido</param>
   ''' <param name="nSelPartId">Id pezzo</param>
   ''' <param name="bSolid">booleano controllo solido</param>
   ''' <param name="bSelPieces">booleano controllo se pezzo selezionato</param>
   Friend Sub ShowAllPieces(bShowBuilding As Boolean, Optional bShowSolid As Boolean = False, Optional nSelPartId As Integer = 0, Optional bSolid As Boolean = False, Optional bSelPieces As Boolean = False)
      If Map.refShowBeamPanelVM.bShowAll Then
         ' verifico se assemblato e lo annullo per salvataggio
         bShowBuilding = Map.refShowBeamPanelVM.ShowBuilding_IsChecked
         If bShowBuilding Then Map.refProjectVM.BTLStructureVM.ShowBuilding(False, False)
         ' se vista singolo pezzo
      ElseIf Not Map.refShowBeamPanelVM.bShowAll AndAlso bSolid Then
         bShowSolid = Map.refShowBeamPanelVM.ShowSolid_IsChecked
         If bShowSolid Then Map.refProjectVM.BTLStructureVM.ShowSolid(GDB_ID.NULL, False, False)
         ' se pezzo selezionato lo segno e metto vista tutti
         If bSelPieces Then
            If Not IsNothing(Map.refProjectVM.BTLStructureVM) AndAlso Not IsNothing(Map.refProjectVM.BTLStructureVM.SelBTLPart) Then nSelPartId = Map.refProjectVM.BTLStructureVM.SelBTLPart.nPartId
            Map.refProjectVM.BTLStructureVM.ShowAll(False)
         End If
      End If
   End Sub

   ''' <summary>
   ''' elimino i pezzi da sovrascrivere nel progetto corrente
   ''' </summary>
   ''' <param name="BTLPartList">Lista BTLPart</param>
   Friend Sub DeletePieces(BTLPartList As ObservableCollection(Of BTLPartToUpdate))
      For Each BTLPartToOverwriteWith In BTLPartList
         If BTLPartToOverwriteWith.bInsert Then
            Dim BTLPartToUpdate As BTLPartVM = Map.refProjectVM.BTLStructureVM.BTLPartVMList.FirstOrDefault(Function(x) x.nPDN = BTLPartToOverwriteWith.nPDN)
            ' se BTLPartToUpdate è Nothing significa che il pezzo è nuovo e quindi basta accodarlo senza eliminare nulla
            If Not IsNothing(BTLPartToUpdate) Then
               Dim nPartToDeleteId As Integer = BTLPartToUpdate.nPartId
               Dim nCurrPartId = EgtGetCurrPart()
               EgtErase(nPartToDeleteId)
               nCurrPartId = EgtGetCurrPart()
               ' verifico se rimuovere sezione dalla lista
               If Not Map.refProjectVM.BTLStructureVM.BTLPartVMList.Any(Function(x) x IsNot BTLPartToUpdate AndAlso x.Section = BTLPartToUpdate.Section) Then
                  Map.refProjectVM.BTLStructureVM.SectionList.Remove(BTLPartToUpdate.Section)
               End If
               ' rimuovo dalla lista pezzi
               Dim Index As Integer = Map.refProjectVM.BTLStructureVM.BTLPartVMList.IndexOf(BTLPartToUpdate)
               Map.refProjectVM.BTLStructureVM.SetSelBTLPart(Nothing)
               Map.refProjectVM.BTLStructureVM.BTLPartVMList.RemoveAt(Index)
            End If
         End If
      Next
   End Sub

   ''' <summary>
   ''' tolgo eventuale indicazione solido rimasta da pezzo precedente
   ''' </summary>
   ''' <param name="nPartId">Id pezzo</param>
   ''' <param name="bShowSolid">booleano visualizzazione solido</param>
   Friend Sub DeselectSolid(Optional nPartId As Integer = 0, Optional bShowSolid As Boolean = False)
      If Map.refShowBeamPanelVM.ShowSolid_IsChecked Then
         ' tolgo eventuale indicazione solido rimasta da pezzo precedente
         Map.refShowBeamPanelVM.SetShowSolid(False)
         If bShowSolid Then Map.refProjectVM.BTLStructureVM.ShowSolid(nPartId, False, False)
      End If
   End Sub

   ''' <summary>
   ''' verifico se la dimensione e' maggiore del box minimo dei pezzi
   ''' </summary>
   ''' <param name="PartVMList"></param>
   ''' <param name="b3Parts"></param>
   Friend Sub VerifyMaxDimension(PartVMList As ObservableCollection(Of Core.PartVM), b3Parts As BBox3d)
      Dim nBoxLayerId As Integer = EgtGetFirstNameInGroup(PartVMList(0).nPartId, "Box")
      EgtGetBBoxGlob(nBoxLayerId, GDB_BB.EXACT, b3Parts)
      For PartIndex = 1 To PartVMList.Count - 1
         Dim b3Part As New BBox3d
         nBoxLayerId = EgtGetFirstNameInGroup(PartVMList(PartIndex).nPartId, "Box")
         EgtGetBBoxGlob(nBoxLayerId, GDB_BB.EXACT, b3Part)
         b3Parts.Add(b3Part)
      Next
   End Sub

   ''' <summary>
   ''' riporto il grezzo nell'angolo tavola di origine
   ''' </summary>
   ''' <param name="b3Tab"></param>
   ''' <param name="nRawPartId"></param>
   Friend Sub SelectCorner(b3Tab As BBox3d, nRawPartId As Integer)
      EgtGetTableArea(1, b3Tab)
      Dim p3OrigOnTab As Point3d
      Select Case CurrentMachine.OrigCorner
         Case MCH_CR.BL
            p3OrigOnTab = New Point3d(CurrentMachine.OrigOffsX, CurrentMachine.OrigOffsY, 0)
         Case MCH_CR.BR
            p3OrigOnTab = New Point3d(b3Tab.DimX() - CurrentMachine.OrigOffsX, CurrentMachine.OrigOffsY, 0)
         Case MCH_CR.TL
            p3OrigOnTab = New Point3d(CurrentMachine.OrigOffsX, b3Tab.DimY() - CurrentMachine.OrigOffsY, 0)
         Case MCH_CR.TR
            p3OrigOnTab = New Point3d(b3Tab.DimX() - CurrentMachine.OrigOffsX, b3Tab.DimY() - CurrentMachine.OrigOffsY, 0)
      End Select
      EgtMoveToCornerRawPart(nRawPartId, p3OrigOnTab, CurrentMachine.OrigCorner)
   End Sub

   ''' <summary>
   ''' 
   ''' </summary>
   ''' <param name="nPartId"></param>
   ''' <param name="BTLStructureVM"></param>
   Friend Sub SelectedPieces(nPartId As Integer, BTLStructureVM As BTLStructureVM)
      EgtBeamShowFacesName(False)
      EgtBeamShowLoadingSide(False, False)
      Map.refProjectVM.MacroFeature_IsEnabled = True
      ' se modalità building, la tolgo
      If Map.refShowBeamPanelVM.ShowBuilding_IsChecked Then
         BTLStructureVM.ShowBuilding(False, False)
      End If

      BTLStructureVM.SceneSelPartSelection()
      ' seleziono pezzo in Db geometrico
      EgtBeamSetPart(nPartId)
      EgtBeamShowFacesName(True)
      Dim bLoadingSideShow As Boolean = (BTLStructureVM.nPROJTYPE = BWType.BEAM)
      Dim bLeftToRight As Boolean = Not (CurrentMachine.ViewDir = VT.ISO_NW OrElse CurrentMachine.ViewDir = VT.ISO_NE)
      EgtBeamShowLoadingSide(bLoadingSideShow, bLeftToRight)
   End Sub

   Public Sub CreatePrintPDF(ActivePage As Integer, bPreview As Boolean)
      LoadingWndHelper.OpenLoadingWnd(ActiveIds.CREATINGPDF, 1, "Creating PDF", "", 100)
      Try
         ' creo documento MigraDoc
         Dim document As Document = PDFHelper.CreateStatReport(ActivePage, bPreview)
         Dim documentPath As String = Map.refMainWindowVM.MainWindowM.sTempDir & "\MigraDoc.mdddl"
         MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToFile(document, documentPath)
         Dim renderer As New PdfDocumentRenderer(True) With {
            .Document = document
         }
         renderer.RenderDocument()
         ' salvo il documento
         Dim sFileName As String = ""

         If (ActivePage = Pages.VIEW AndAlso Not bPreview) OrElse (ActivePage = Pages.ONLYPRODPAGE AndAlso Not Map.refInstrumentPanelVM.bVisOtt_Selected AndAlso Not bPreview) Then
            sFileName = ProjectManagerVM.CurrProj.sProjDirPath & "\" & "Statistics.pdf"
         ElseIf ActivePage = Pages.VIEW OrElse Pages.ONLYPRODPAGE AndAlso bPreview Then
            sFileName = Map.refMainWindowVM.MainWindowM.sTempDir & "\Statistics.pdf"  ' Se la pagina e' 0 e' bPreview e' True creo PDF Visualization
         ElseIf (ActivePage = Pages.MACHINING AndAlso Not bPreview) OrElse (ActivePage = Pages.ONLYPRODPAGE AndAlso Map.refInstrumentPanelVM.bVisOtt_Selected AndAlso Not bPreview) Then
            sFileName = ProjectManagerVM.CurrProd.sProdDirPath & "\" & ProjectManagerVM.CurrProd.sProdId & " - " & "Statistics.pdf"
         ElseIf ActivePage = Pages.MACHINING OrElse Pages.ONLYPRODPAGE AndAlso bPreview Then ' Se la pagina e' 1 e' bPreview e' True creo PDF Optimizer
            sFileName = Map.refMainWindowVM.MainWindowM.sTempDir & "\Statistics.pdf"
            PrevSelect()
         End If

         ' avvio il visualizzatore 
         renderer.PdfDocument.Save(sFileName)
         ' cancello file MigraDoc
         System.IO.File.Delete(documentPath)

         If bPreview Then
         Else
            Process.Start(sFileName)
         End If
      Catch ex As Exception
         EgtOutLog("Error genereting pdf: " & ex.ToString())
      End Try
      LoadingWndHelper.CloseLoadingWnd(ActiveIds.CREATINGPDF)

   End Sub

   Private Sub PrevSelect()
      ' ripristino selezione precedente
      Dim nCurrMachGroupId As Integer = EgtGetCurrMachGroup()
      If Not IsNothing(Map.refProjectVM.MachGroupPanelVM.SelectedMachGroup) AndAlso nCurrMachGroupId <> Map.refProjectVM.MachGroupPanelVM.SelectedMachGroup.Id Then
         EgtSetCurrMachGroup(Map.refProjectVM.MachGroupPanelVM.SelectedMachGroup.Id)
      End If
      Core.ViewPanelVM.BWSetView(If(Core.ViewPanelVM.Type = BWType.BEAM, VT.ISO_SW, VT.TOP), False)
      EgtZoom(ZM.ALL, True)
   End Sub

End Module
