Imports System.Collections.ObjectModel
Imports System.IO
Imports EgtUILib
Imports System.Runtime.InteropServices

Public Class ImportPageUC

   ' Riferimento alla MainWindow
   Private m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
   ' Dichiarazione SceneButtons
   Friend m_SceneButtons As SceneButtonsUC
   ' Dichiarazione SideAngleUC
   Friend m_SideAngleUC As SideAngleUC
   ' Dichiarazione UnderDrillUC
   Friend m_UnderDrillUC As UnderDrillUC
   ' Dichiarazione FiloTopUC
   Friend m_FiloTopUC As FiloTopUC
   ' Dichiarazione Scene
   Friend WithEvents ImportScene As New Scene
   Private ImportSceneHost As New System.Windows.Forms.Integration.WindowsFormsHost

   ' Properties
   Private m_sCurrDir As String = String.Empty
   Private m_sCurrFile As String = String.Empty
   Private m_nFileType As Integer = FT.NULL
   Private m_bFirst As Boolean = True
   Private m_bMM As Boolean = True
   Private m_bEnableTrf As Boolean = False
   Private m_bEnableOrderList As Boolean = False
   Private m_sOrder As String = ""
   Private m_sList As String = ""
   Private m_sCad2dPath As String = ""
   Private m_sCad2dName As String = ""
   ' Costante per formato TRF
   Private Const FT_TRF As Integer = 51
   ' Costante per formato CUT
   Private Const FT_CUT As Integer = 52

   ' Indentificativo del pezzo selezionato
   Private m_nSelectedPart As Integer = GDB_ID.NULL
   Friend ReadOnly Property SelectedPart As Integer
      Get
         Return m_nSelectedPart
      End Get
   End Property
   ' Indentificativo del layer selezionato
   Private m_nSelectedLayer As Integer = GDB_ID.NULL
   Friend ReadOnly Property SelectedLayer As Integer
      Get
         Return m_nSelectedLayer
      End Get
   End Property

   Private Sub ImportPage_Initialized(sender As Object, e As EventArgs)

      ' Creazione degli UserControl
      m_SceneButtons = New SceneButtonsUC
      m_SideAngleUC = New SideAngleUC
      m_UnderDrillUC = New UnderDrillUC
      m_FiloTopUC = New FiloTopUC

      ' Posizionemento nella griglia degli UserControl
      m_SceneButtons.SetValue(Grid.ColumnProperty, 5)
      m_SideAngleUC.SetValue(Grid.RowProperty, 2)
      m_UnderDrillUC.SetValue(Grid.RowProperty, 2)
      m_FiloTopUC.SetValue(Grid.RowProperty, 2)
      UpperButtonGrid.Children.Add(m_SceneButtons)

      'Assegnazione scena all'host e posizionamento nella ImportPageGrid
      ImportSceneHost.Child = ImportScene
      ImportSceneHost.SetValue(Grid.ColumnProperty, 1)
      ImportSceneHost.SetValue(Grid.RowProperty, 1)
      Me.ImportPageGrid.Children.Add(ImportSceneHost)

      'Imposto i messaggi letti dal file dei messaggi
      UseLayerBtn.Content = EgtMsg(MSG_IMPORTPAGEUC + 1)              'Usa layer - Use layers
      UseRegionBtn.Content = EgtMsg(MSG_IMPORTPAGEUC + 2)             'Usa regioni - Use regions
      UseClosedCurveBtn.Content = EgtMsg(MSG_IMPORTPAGEUC + 6)        'Usa curve chiuse - Use closed curves
      ResetBtn.Content = EgtMsg(MSG_IMPORTPAGEUC + 3)                 'Reset
      mmBtn.Content = EgtMsg(MSG_IMPORTPAGEUC + 4)                    'mm
      inchBtn.Content = EgtMsg(MSG_IMPORTPAGEUC + 5)                  'inch
      OrderListBtn.Content = EgtMsg( 90398)                           'Dati Csv
      TopBtn.Content = EgtMsg( 90384)                                 'Indica Lato Sopra
      PartNumTxBl.Text = EgtMsg(MSG_IMPORTPAGEUC + 15)                'Numero
      SideAngleBtn.Content = EgtMsg(MSG_IMPORTPAGEUC + 7)             'Inclina lati
      FiloTopBtn.Content = EgtMsg( 90400)                             'Filo Top
      DripCutBtn.Content = EgtMsg(MSG_IMPORTPAGEUC + 8)               'Incidi da sotto
      DripDrillBtn.Content = EgtMsg(MSG_IMPORTPAGEUC + 14)            'Foro da sotto
      Cad2dBtn.Content = "Cad 2d"

      'Definizione del collegamento tra ItemList e ListBox1
      FileListBox.ItemsSource = m_MainWindow.m_ImportItemList

   End Sub

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

      ' abilitazione importazione TRF
      m_bEnableTrf = (m_MainWindow.m_PrevActivePage = MainWindow.Pages.CadCut And
                      m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.TRF_IMPORT))
      ' abilitazione Ordine e Distinta per importazione DXF
      m_bEnableOrderList = (m_MainWindow.m_PrevActivePage = MainWindow.Pages.CadCut And
                            GetPrivateProfileInt(S_COMPO, K_CSVDATA, 0, m_MainWindow.GetIniFile()) <> 0)

      If m_bFirst Then
         ' imposto colore di default
         Dim DefColor As New Color3d(0, 0, 0)
         GetPrivateProfileColor(S_GEOMDB, K_DEFAULTCOLOR, DefColor, m_MainWindow.GetIniFile())
         ImportScene.SetDefaultMaterial(DefColor)
         ' imposto colori sfondo
         ImportScene.SetViewBackground(GetBackTopColor(), GetBackBottomColor())
         ' imposto colore di evidenziazione
         Dim MarkColor As New Color3d(255, 255, 0)
         GetPrivateProfileColor(S_SCENE, K_MARK, MarkColor, m_MainWindow.GetIniFile())
         ImportScene.SetMarkMaterial(MarkColor)
         ' imposto colore per superfici selezionate
         Dim SelSurfColor As New Color3d(255, 255, 192)
         GetPrivateProfileColor(S_SCENE, K_SELSURF, SelSurfColor, m_MainWindow.GetIniFile())
         ImportScene.SetSelSurfMaterial(SelSurfColor)
         ' imposto tipo e colore del rettangolo di zoom
         Dim bOutline As Boolean = True
         Dim ZwColor As New Color3d(0, 0, 0)
         GetPrivateProfileZoomWin(S_SCENE, K_ZOOMWIN, bOutline, ZwColor, m_MainWindow.GetIniFile())
         ImportScene.SetZoomWinAttribs(bOutline, ZwColor)
         ' imposto colore della linea di distanza
         Dim DstLnColor As New Color3d(255, 0, 0)
         GetPrivateProfileColor(S_SCENE, K_DISTLINE, DstLnColor, m_MainWindow.GetIniFile())
         ImportScene.SetDistLineMaterial(DstLnColor)
         ' imposto parametri OpenGL
         Dim nDriver As Integer = GetPrivateProfileInt(S_OPENGL, K_DRIVER, 3, m_MainWindow.GetIniFile())
         Dim b2Buff As Boolean = (GetPrivateProfileInt(S_OPENGL, K_DOUBLEBUFFER, 1, m_MainWindow.GetIniFile()) <> 0)
         Dim nColorBits As Integer = GetPrivateProfileInt(S_OPENGL, K_COLORBITS, 32, m_MainWindow.GetIniFile())
         Dim nDepthBits As Integer = GetPrivateProfileInt(S_OPENGL, K_DEPTHBITS, 32, m_MainWindow.GetIniFile())
         ImportScene.SetViewAttributes(nDriver, b2Buff, nColorBits, nDepthBits)
         ' Inizializzazione delle viste
         ImportScene.Init()
         ' dimensione lineare max in pixel delle textures
         Dim nTxrMaxLinPix As Integer = GetPrivateProfileInt(S_SCENE, K_TEXMAXLINPIX, 4096, m_MainWindow.GetIniFile())
         EgtSetTextureMaxLinPixels(nTxrMaxLinPix)
         ' Imposto griglia
         LoadGridData()
         ' leggo direttorio corrente
         GetPrivateProfileString(S_FLATPARTS, K_FLPCURRDIR, "", m_sCurrDir, m_MainWindow.GetIniFile())
         ' lo carico
         LoadCurrDir()
         m_bFirst = False
      Else
         ' Imposto contesto
         EgtSetCurrentContext(ImportScene.GetCtx())
         ' Imposto griglia
         LoadGridData()
      End If

      ' Verifico esistenza Cad 2d
      GetPrivateProfileString(S_CAD2D, K_CAD2D_NAME, "", m_sCad2dName, m_MainWindow.GetIniFile())
      GetPrivateProfileString(S_CAD2D, K_CAD2D_EXEPATH, "", m_sCad2dPath, m_MainWindow.GetIniFile())
      Cad2dBtn.IsEnabled = My.Computer.FileSystem.FileExists( m_sCad2dPath)

      ' Pulisco tutto
      ClearView()
      FileListBox.UnselectAll()
      ' inibisco selezione diretta da Scene
      ImportScene.SetStatusNull()

      ' visualizzazione bottoni
      If m_MainWindow.m_PrevActivePage = MainWindow.Pages.CadCut Then
         UseLayerBtn.Visibility = Windows.Visibility.Visible
         UseRegionBtn.Visibility = Windows.Visibility.Visible
         UseClosedCurveBtn.Visibility = Windows.Visibility.Visible
         ResetBtn.Visibility = Windows.Visibility.Visible
         SideAngleBtn.Visibility = Windows.Visibility.Visible
         OrderListBtn.Visibility = If( m_bEnableOrderList, Windows.Visibility.Visible, Windows.Visibility.Hidden)
         TopBtn.Visibility = Windows.Visibility.Visible
         PartNumberGrd.Visibility = Windows.Visibility.Visible
      Else
         UseLayerBtn.Visibility = Windows.Visibility.Hidden
         UseRegionBtn.Visibility = Windows.Visibility.Hidden
         UseClosedCurveBtn.Visibility = Windows.Visibility.Hidden
         ResetBtn.Visibility = Windows.Visibility.Hidden
         SideAngleBtn.Visibility = Windows.Visibility.Hidden
         OrderListBtn.Visibility = Windows.Visibility.Hidden
         TopBtn.Visibility = Windows.Visibility.Hidden 
         PartNumberGrd.Visibility = Windows.Visibility.Hidden
      End If
      mmBtn.IsEnabled = True
      inchBtn.IsEnabled = True

      ' imposto misura
      m_bMM = EgtUiUnitsAreMM()
      If m_bMM Then
         mmBtn.IsChecked = True
      Else
         inchBtn.IsChecked = True
      End If
      ' imposto quantità
      PartNumTxBx.Text = "1"
      ' disabilito ok
      OkBtn.IsEnabled = False

   End Sub

   Private Sub LoadGridData()
      Dim dSnapStep As Double = If(EgtUiUnitsAreMM(),
                                   GetPrivateProfileDouble(S_GRID, K_SNAPSTEP, 10, m_MainWindow.GetIniFile()),
                                   GetPrivateProfileDouble(S_GRID, K_SNAPSTEPINCH, 12.7, m_MainWindow.GetIniFile()))
      Dim nMinLineSStep As Integer = GetPrivateProfileInt(S_GRID, K_MINLINESSTEP, 1, m_MainWindow.GetIniFile())
      Dim nMajLineSStep As Integer = GetPrivateProfileInt(S_GRID, K_MAJLINESSTEP, 10, m_MainWindow.GetIniFile())
      Dim nExtSStep As Integer = GetPrivateProfileInt(S_GRID, K_EXTSSTEP, 50, m_MainWindow.GetIniFile())
      Dim MinLnColor As New Color3d(160, 160, 160)
      GetPrivateProfileColor(S_GRID, K_MINLNCOLOR, MinLnColor, m_MainWindow.GetIniFile())
      Dim MajLnColor As New Color3d(160, 160, 160)
      GetPrivateProfileColor(S_GRID, K_MAJLNCOLOR, MajLnColor, m_MainWindow.GetIniFile())
      EgtSetGridFrame(Frame3d.GLOB)
      EgtSetGridGeo(dSnapStep, nMinLineSStep, nMajLineSStep, nExtSStep)
      EgtSetGridColor(MinLnColor, MajLnColor)
      Dim bShowGrid As Boolean = (GetPrivateProfileInt(S_GRID, K_SHOWGRID, 1, m_MainWindow.GetIniFile()) <> 0)
      EgtSetGridShow(bShowGrid, False)
   End Sub

   Private Function LoadCurrDir() As Boolean
      ' se direttorio corrente non valido, carico l'elenco dei dischi
      If String.IsNullOrWhiteSpace(m_sCurrDir) OrElse Not IO.Directory.Exists(m_sCurrDir) Then
         Return LoadDisks()
      End If
      Dim TempPath As New Text.StringBuilder(260)
      PathCompactPathEx(TempPath, m_sCurrDir, 22, 0)
      ' lo visualizzo
      FilePathTxBl.Text = TempPath.ToString
      ' pulisco la lista
      m_MainWindow.m_ImportItemList.Clear()
      ' per risalire al direttorio padre
      m_MainWindow.m_ImportItemList.Add(New IconListBoxItem("..", 0))
      ' elenco dei sottodirettori
      Dim DirInfo As New DirectoryInfo(m_sCurrDir)
      Dim vDirI As DirectoryInfo() = DirInfo.GetDirectories("*")
      Dim DirI As DirectoryInfo
      For Each DirI In vDirI
         ' per saltare i link, troppo complessi da gestire
         If (DirI.Attributes And FileAttributes.Hidden) <> FileAttributes.Hidden Or
            (DirI.Attributes And FileAttributes.System) <> FileAttributes.System Then
            m_MainWindow.m_ImportItemList.Add(New IconListBoxItem(DirI.Name, 2))
         End If
      Next
      ' elenco dei file
      Dim vFileI As FileInfo() = DirInfo.GetFiles()
      Dim FileI As FileInfo
      For Each FileI In vFileI
         Dim sExt As String = Path.GetExtension(FileI.Name).ToUpper()
         If sExt = ".DXF" Or sExt = ".NGE" Or (m_bEnableTrf And sExt = ".TRF") Then
            m_MainWindow.m_ImportItemList.Add(New IconListBoxItem(FileI.Name, 3))
         End If
      Next
      ' pulisco la vista
      ClearView()
      Return True
   End Function

   Private Function LoadDisks() As Boolean
      ' dir corrente vuoto
      m_sCurrDir = ""
      ' lo visualizzo
      FilePathTxBl.Text = m_sCurrDir
      ' pulisco la lista
      m_MainWindow.m_ImportItemList.Clear()
      ' elenco dei dischi
      Dim vDriI As DriveInfo() = DriveInfo.GetDrives()
      Dim DriI As DriveInfo
      For Each DriI In vDriI
         m_MainWindow.m_ImportItemList.Add(New IconListBoxItem(DriI.Name, 1))
      Next
      ' pulisco la vista
      ClearView()
      Return True
   End Function

   Private Sub FileListBox_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles FileListBox.SelectionChanged
      ' Recupero item selezionato
      If FileListBox.SelectedItems.Count() = 0 Then Return
      Dim vItems As IconListBoxItem = FileListBox.SelectedItems(0)
      ' A seconda del tipo
      Select Case vItems.PictureID
         Case 0        ' Vai nel direttorio padre
            m_sCurrDir = IO.Path.GetDirectoryName(m_sCurrDir)
            m_sCurrFile = ""
            LoadCurrDir()
         Case 1        ' Vai nella radice del disco
            m_sCurrDir = vItems.Name
            m_sCurrFile = ""
            LoadCurrDir()
         Case 2        ' Vai nel sottodirettorio
            m_sCurrDir = IO.Path.Combine(m_sCurrDir, vItems.Name)
            m_sCurrFile = ""
            LoadCurrDir()
         Case 3        ' File
            m_sCurrFile = vItems.Name
            LoadCurrFile()
      End Select
   End Sub

   Private Function ClearView() As Boolean
      ' Pulisco il DB geometrico locale
      EgtNewFile()
      ' Eseguo zoom
      ImportScene.ZoomAll()
      ' disabilito bottoni Process e Insert
      UseLayerBtn.IsEnabled = False
      UseClosedCurveBtn.IsEnabled = False
      UseRegionBtn.IsEnabled = False
      ResetBtn.IsEnabled = False
      SideAngleBtn.IsEnabled = False
      FiloTopBtn.IsEnabled = False
      DripCutBtn.IsEnabled = False
      DripDrillBtn.IsEnabled = False
      Return True
   End Function

   Private Function LoadCurrFile() As Boolean
      ' Pulisco il DB geometrico locale
      Dim bOk As Boolean = EgtNewFile()
      ' Costruisco path completa del file
      Dim sPath = IO.Path.Combine(m_sCurrDir, m_sCurrFile)
      ' Riconoscimento tipo
      m_nFileType = EgtGetFileType(sPath)
      If m_nFileType = FT.NULL And m_bEnableTrf And Path.GetExtension(sPath).ToUpper() = ".TRF" Then m_nFileType = FT_TRF
      If m_nFileType = FT.DXF Then
         ' recupero unità di misura del file
         Dim dScale As Double = If(m_bMM, ONEMM, ONEINCH)
         ' Importo file DXF
         bOk = bOk AndAlso EgtImportDxf(sPath, dScale)
      ElseIf m_nFileType = FT.NGE Then
         ' Carico Nge
         bOk = bOk AndAlso EgtOpenFile(sPath)
         ' Verifico se progetto OmagCut
         If EgtGetFirstNameInGroup(GDB_ID.ROOT, NAME_PROJMARK) <> GDB_ID.NULL Then
            Dim bIsFrame As Boolean = (EgtGetFirstNameInGroup(GDB_ID.ROOT, NAME_FRAME) <> GDB_ID.NULL)
            If (m_MainWindow.m_PrevActivePage = MainWindow.Pages.CadCut And Not bIsFrame) Or
               (m_MainWindow.m_PrevActivePage = MainWindow.Pages.FrameCut And bIsFrame) Then
               m_nFileType = FT_CUT
            End If
         End If
         ' Filtro Nge
         bOk = bOk AndAlso FilterNge(m_nFileType = FT.NGE)
      ElseIf m_nFileType = FT_TRF Then
         ' Carico Trf
         bOk = bOk AndAlso ImportTrf(sPath)
      Else
         ' Formato sconosciuto
         bOk = False
      End If
      ' Eseguo zoom
      ImportScene.ZoomAll()
      ' Se import per pezzi piatti
      If m_MainWindow.m_PrevActivePage = MainWindow.Pages.CadCut Then
         ' se formato DXF o NGE
         If m_nFileType = FT.DXF Or m_nFileType = FT.NGE Then
            ' abilito bottoni UseLayer, UseClosedCurve e UseRegion, disabilito Reset e Insert
            UseLayerBtn.IsEnabled = True
            UseClosedCurveBtn.IsEnabled = True
            UseRegionBtn.IsEnabled = True
            ResetBtn.IsEnabled = False
            mmBtn.IsEnabled = (m_nFileType = FT.DXF)
            inchBtn.IsEnabled = (m_nFileType = FT.DXF)
            OrderListBtn.IsEnabled = m_bEnableOrderList
            TopBtn.IsEnabled = True
            PartNumberGrd.IsEnabled = True
            OkBtn.IsEnabled = False
            SideAngleBtn.IsEnabled = False
            FiloTopBtn.IsEnabled = False
            DripCutBtn.IsEnabled = False
            DripDrillBtn.IsEnabled = False
         ElseIf m_nFileType = FT_TRF Or m_nFileType = FT_CUT Then
            ' abilito bottone Insert, disabilito bottoni UseLayer, UseClosedCurve, UseRegion e Reset
            UseLayerBtn.IsEnabled = False
            UseClosedCurveBtn.IsEnabled = False
            UseRegionBtn.IsEnabled = False
            ResetBtn.IsEnabled = False
            mmBtn.IsEnabled = False
            inchBtn.IsEnabled = False
            OrderListBtn.IsEnabled = False
            TopBtn.IsEnabled = False
            PartNumberGrd.IsEnabled = False
            OkBtn.IsEnabled = True
            SideAngleBtn.IsEnabled = False
            FiloTopBtn.IsEnabled = False
            DripCutBtn.IsEnabled = False
            DripDrillBtn.IsEnabled = False
         End If
      ' altrimenti import per cornici
      Else
         mmBtn.IsEnabled = (m_nFileType = FT.DXF)
         inchBtn.IsEnabled = (m_nFileType = FT.DXF)
         OkBtn.IsEnabled = True
      End If
      Return bOk
   End Function

   Private Sub OnMouseDownScene(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ImportScene.OnMouseDownScene
      If SideAngleBtn.IsChecked() Or DripCutBtn.IsChecked() Then
         OnMouseDownSceneSideAngle( e)
      ElseIf DripDrillBtn.IsChecked() Then
         OnMouseDownSceneUnderDrill( e)
      ElseIf FiloTopBtn.IsChecked() Then
         OnMouseDownSceneFiloTop( e)
      End If
   End Sub

   Private Sub OnMouseDownSceneSideAngle(e As System.Windows.Forms.MouseEventArgs)
      ' Solo con il tasto sinistro e se stato NULL
      If e.Button <> Windows.Forms.MouseButtons.Left Or Not ImportScene.IsStatusNull() Then Return
      ' Verifico se selezionato indicativo di pezzo
      EgtSetObjFilterForSelWin(False, False, True, False, False)
      Dim nSel As Integer
      EgtSelect(e.Location, Scene.DIM_SEL, Scene.DIM_SEL, nSel)
      Dim nId As Integer = EgtGetFirstObjInSelWin()
      While nId <> GDB_ID.NULL
         ' Recupero l'identificativo del layer e del pezzo cui appartiene
         Dim nRegLayId As Integer = EgtGetParent(nId)
         Dim nPartId As Integer = EgtGetParent(nRegLayId)
         If EgtIsPart(nPartId) Then
            Dim sRegLayName As String = String.Empty
            EgtGetName(nRegLayId, sRegLayName)
            If sRegLayName = NAME_REGION Or sRegLayName = SELECT_REGION_LAYER Then
               Dim nStat As Integer = GDB_ST.ON_
               EgtGetStatus(nId, nStat)
               If nStat = GDB_ST.SEL Then
                  EgtDeselectAll()
                  m_nSelectedPart = GDB_ID.NULL
                  m_nSelectedLayer = GDB_ID.NULL
                  SideAngle.WriteSideAngleForNest(ImportScene.GetCtx())
                  ' Messaggio di selezione da effettuare
                  MessageTxBx.Text = EgtMsg(MSG_DRAWPAGEUC + 6)   ' Selezionare un contorno
                  MessageBrd.Background = Application.Current.FindResource("OmagCut_Green")
               Else
                  Dim nLayId As Integer = EgtGetFirstNameInGroup(nPartId, NAME_OUTLOOP)
                  EgtGetInfo(nId, "ID", nLayId)
                  ' prima deseleziono eventuale pezzo già selezionato
                  EgtDeselectAll()
                  m_nSelectedPart = GDB_ID.NULL
                  m_nSelectedLayer = GDB_ID.NULL
                  SideAngle.WriteSideAngleForNest(ImportScene.GetCtx())
                  ' seleziono pezzo cliccato
                  EgtSelectObj(nId)
                  EgtSelectObj(nLayId)
                  m_nSelectedPart = nPartId
                  m_nSelectedLayer = nLayId
                  ' Pulisco area messaggi
                  MessageTxBx.Text = ""
                  MessageBrd.Background = Brushes.Transparent
               End If
               SelectedPartChanged()
               EgtDraw()
               Exit While
            End If
         End If
         nId = EgtGetNextObjInSelWin()
      End While
   End Sub

   Private Sub OnMouseDownSceneUnderDrill(e As System.Windows.Forms.MouseEventArgs)
      ' Solo con il tasto sinistro e se stato NULL
      If e.Button <> Windows.Forms.MouseButtons.Left Or Not ImportScene.IsStatusNull() Then Return
      ' Verifico se selezionato indicativo di pezzo
      EgtSetObjFilterForSelWin(False, False, True, False, False)
      Dim nSel As Integer
      EgtSelect(e.Location, Scene.DIM_SEL, Scene.DIM_SEL, nSel)
      Dim nId As Integer = EgtGetFirstObjInSelWin()
      While nId <> GDB_ID.NULL
         ' Recupero l'identificativo del layer e del pezzo cui appartiene
         Dim nRegLayId As Integer = EgtGetParent(nId)
         Dim nPartId As Integer = EgtGetParent(nRegLayId)
         If EgtIsPart(nPartId) Then
            Dim sRegLayName As String = String.Empty
            EgtGetName(nRegLayId, sRegLayName)
            If sRegLayName = NAME_REGION Or sRegLayName = SELECT_REGION_LAYER Then
               Dim nStat As Integer = GDB_ST.ON_
               EgtGetStatus(nId, nStat)
               If nStat = GDB_ST.SEL Then
                  Dim nLayId As Integer = GDB_ID.NULL
                  EgtGetInfo(nId, "ID", nLayId)
                  EgtDeselectObj(nId)
                  EgtDeselectObj(nLayId)
                  Dim sLayName As String = ""
                  If EgtGetName(nLayId, sLayName) And sLayName = NAME_UNDERDRILL Then
                     EgtSetName(nLayId, NAME_INLOOP)
                     Dim nEntId As Integer = EgtGetFirstInGroup(nLayId)
                     EgtRemoveInfo(nEntId, INFO_DEPTH)
                     EgtSetColor(nEntId, New Color3d(127, 63, 0))
                  End If
               Else
                  Dim nLayId As Integer = GDB_ID.NULL
                  EgtGetInfo(nId, "ID", nLayId)
                  Dim sLayName As String = ""
                  If EgtGetName(nLayId, sLayName) And (sLayName = NAME_INLOOP) Then
                     EgtSelectObj(nId)
                     EgtSelectObj(nLayId)
                     EgtSetName(nLayId, NAME_UNDERDRILL)
                     Dim nEntId As Integer = EgtGetFirstInGroup(nLayId)
                     EgtSetInfo(nEntId, INFO_DEPTH, m_UnderDrillUC.DrillDepth)
                     EgtSetColor(nEntId, New Color3d(255, 255, 255))
                  End If
               End If
               EgtDraw()
            End If
         End If
         nId = EgtGetNextObjInSelWin()
      End While
   End Sub

   Private Sub OnMouseDownSceneFiloTop(e As System.Windows.Forms.MouseEventArgs)
      ' Solo con il tasto sinistro e se stato NULL
      If e.Button <> Windows.Forms.MouseButtons.Left Or Not ImportScene.IsStatusNull() Then Return
      ' Verifico se selezionato indicativo di pezzo
      EgtSetObjFilterForSelWin(False, False, True, False, False)
      Dim nSel As Integer
      EgtSelect(e.Location, Scene.DIM_SEL, Scene.DIM_SEL, nSel)
      Dim nId As Integer = EgtGetFirstObjInSelWin()
      While nId <> GDB_ID.NULL
         ' Recupero l'identificativo del layer e del pezzo cui appartiene
         Dim nRegLayId As Integer = EgtGetParent(nId)
         Dim nPartId As Integer = EgtGetParent(nRegLayId)
         If EgtIsPart(nPartId) Then
            Dim sRegLayName As String = String.Empty
            EgtGetName(nRegLayId, sRegLayName)
            If sRegLayName = NAME_REGION Or sRegLayName = SELECT_REGION_LAYER Then
               Dim nStat As Integer = GDB_ST.ON_
               EgtGetStatus(nId, nStat)
               If nStat = GDB_ST.SEL Then
                  Dim nLayId As Integer = GDB_ID.NULL
                  EgtGetInfo(nId, "ID", nLayId)
                  EgtDeselectObj(nId)
                  EgtDeselectObj(nLayId)
                  Dim sLayName As String = ""
                  If EgtGetName(nLayId, sLayName) AndAlso sLayName = NAME_INLOOP AndAlso EgtExistsInfo( nLayId, INFO_FILOTOP) Then
                     EgtRemoveInfo( nLayId, INFO_FILOTOP)
                     EgtRemoveInfo( nLayId, INFO_OFFSET)
                     EgtRemoveInfo( nLayId, INFO_DEPTH)
                     Dim nEntId As Integer = EgtGetFirstInGroup( nLayId)
                     While nEntId <> GDB_ID.NULL
                        EgtSetColor(nEntId, New Color3d(127, 63, 0))
                        nEntId = EgtGetNext( nEntId)
                     End While
                  End If
               Else
                  Dim nLayId As Integer = GDB_ID.NULL
                  EgtGetInfo(nId, "ID", nLayId)
                  Dim sLayName As String = ""
                  If EgtGetName( nLayId, sLayName) AndAlso sLayName = NAME_INLOOP Then
                     EgtSelectObj( nId)
                     EgtSelectObj( nLayId)
                     EgtSetInfo( nLayId, INFO_FILOTOP, 1)
                     EgtSetInfo( nLayId, INFO_OFFSET, m_FiloTopUC.FiloTopOffset)
                     EgtSetInfo( nLayId, INFO_DEPTH, m_FiloTopUC.FiloTopDepth)
                     Dim nEntId As Integer = EgtGetFirstInGroup( nLayId)
                     While nEntId <> GDB_ID.NULL
                        EgtSetColor(nEntId, New Color3d(255, 255, 255))
                        nEntId = EgtGetNext( nEntId)
                     End While
                  End If
               End If
               EgtDraw()
            End If
         End If
         nId = EgtGetNextObjInSelWin()
      End While
   End Sub

   Private Sub OnShowDistanceVector(sender As Object, vtDist As Vector3d) Handles ImportScene.OnShowDistanceVector
      MessageTxBx.Text = DistToString(vtDist)
      MessageBrd.Background = Application.Current.FindResource("OmagCut_Green")
   End Sub

   Private Sub SelectedPartChanged()
      ' Se sono in modalità inclinazioni o gocciolatoio calcolo lati inclinabili e creo testi
      If SideAngleBtn.IsChecked() Or DripCutBtn.IsChecked() Then
         m_SideAngleUC.ReLoadSideAnglePage()
      End If
   End Sub

   ' metodo utilizzato per definire il colore dei pezzi DXF importati
   Private Sub ColorRegion(nCtx As Integer)

      ' Leggo dati corrispondenza colore
      Dim InsertColor As Color3d = CompoColor(m_MainWindow.GetIniFile())

      ' Imposto contesto corrente
      EgtSetCurrentContext(nCtx)
      ' Ciclo sui pezzi
      Dim PartId As Integer = EgtGetFirstPart()
      While PartId <> GDB_ID.NULL
         ' Ciclo sui layer delle regioni
         Dim RegionId As Integer = EgtGetFirstNameInGroup(PartId, NAME_REGION)
         While RegionId <> GDB_ID.NULL
            EgtSetColor(RegionId, InsertColor)
            ' Ciclo sulle regioni
            Dim EntId As Integer = EgtGetFirstInGroup(RegionId)
            While EntId <> GDB_ID.NULL
               If EgtGetType( EntId) = GDB_TY.SRF_FRGN Then EgtSetColor(EntId, InsertColor)
               EntId = EgtGetNext(EntId)
            End While
            RegionId = EgtGetNextName(PartId, NAME_REGION)
         End While
         ' passo al pezzo successico
         PartId = EgtGetNextPart(PartId)
      End While
      ' Aggiorno scritte per angoli sui lati
      WriteSideAngleForNest(nCtx)
   End Sub

   Private Sub UseLayerBtn_Click(sender As Object, e As RoutedEventArgs) Handles UseLayerBtn.Click
      ' Creo i pezzi
      Dim nType As Integer = If(m_nFileType = FT.NGE, FPC_TYPE.NGE, FPC_TYPE.LAYER)
      Dim dToler As Double = GetPrivateProfileDouble(S_FLATPARTS, K_FLPTOLERANCE, 0.1, m_MainWindow.GetIniFile())
      EgtCreateAdjustFlatParts(nType, dToler)
      ' Se prevista gestione colore->angolo di fianco
      If GetPrivateProfileInt(S_COLORTOSIDEANG, K_CTSA_ENABLE, 0, m_MainWindow.GetIniFile()) <> 0 Then
         SideAngle.ColorToSideAngle(ImportScene.GetCtx())
      End If
      ' Se prevista gestione colore->incisioni
      If GetPrivateProfileInt(S_COLORTOENGRAVE, K_CTE_ENABLE, 0, m_MainWindow.GetIniFile()) <> 0 Then
         Engrave.ColorToEngrave(ImportScene.GetCtx())
      End If
      ' gestico il colore degli elementi da importare (devono avere una regione definita!
      ColorRegion(ImportScene.GetCtx())
      ' Eseguo zoom
      ImportScene.ZoomAll()
      ' disabilito bottoni UseLayer e UseRegion, abilito bottoni Reset e Insert
      UseLayerBtn.IsEnabled = False
      UseClosedCurveBtn.IsEnabled = False
      UseRegionBtn.IsEnabled = False
      ResetBtn.IsEnabled = True
      OkBtn.IsEnabled = True
      ' abilito bottone angoli su lati esterni
      SideAngleBtn.IsEnabled = m_MainWindow.m_DrawPageUC.bEnableSideAngle
      FiloTopBtn.IsEnabled = m_MainWindow.m_CurrentMachine.bMilling
      DripCutBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                             Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripSaw)
      DripDrillBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                               Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripDrill)
   End Sub

   Private Sub UseClosedCurveBtn_Click(sender As Object, e As RoutedEventArgs) Handles UseClosedCurveBtn.Click
      ' Creo i pezzi
      Dim nType As Integer = If(m_nFileType = FT.NGE, FPC_TYPE.NGE, FPC_TYPE.CLOSEDCURVE)
      Dim dToler As Double = GetPrivateProfileDouble(S_FLATPARTS, K_FLPTOLERANCE, 0.1, m_MainWindow.GetIniFile())
      EgtCreateAdjustFlatParts(nType, dToler)
      ' Se prevista gestione colore->angolo di fianco
      If GetPrivateProfileInt(S_COLORTOSIDEANG, K_CTSA_ENABLE, 0, m_MainWindow.GetIniFile()) <> 0 Then
         SideAngle.ColorToSideAngle(ImportScene.GetCtx())
      End If
      ' Se prevista gestione colore->incisioni
      If GetPrivateProfileInt(S_COLORTOENGRAVE, K_CTE_ENABLE, 0, m_MainWindow.GetIniFile()) <> 0 Then
         Engrave.ColorToEngrave(ImportScene.GetCtx())
      End If
      ' gestico il colore degli elementi da importare (devono avere una regione definita!
      ColorRegion(ImportScene.GetCtx())
      ' Eseguo zoom
      ImportScene.ZoomAll()
      ' disabilito bottoni UseLayer e UseRegion, abilito bottoni Reset e Insert
      UseLayerBtn.IsEnabled = False
      UseClosedCurveBtn.IsEnabled = False
      UseRegionBtn.IsEnabled = False
      ResetBtn.IsEnabled = True
      OkBtn.IsEnabled = True
      ' abilito bottone angoli su lati esterni
      SideAngleBtn.IsEnabled = m_MainWindow.m_DrawPageUC.bEnableSideAngle
      FiloTopBtn.IsEnabled = m_MainWindow.m_CurrentMachine.bMilling
      DripCutBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                             Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripSaw)
      DripDrillBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                               Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripDrill)
   End Sub

   Private Sub UseRegionBtn_Click(sender As Object, e As RoutedEventArgs) Handles UseRegionBtn.Click
      ' Creo i pezzi
      Dim nType As Integer = If(m_nFileType = FT.NGE, FPC_TYPE.NGE, FPC_TYPE.REGION)
      Dim dToler As Double = GetPrivateProfileDouble(S_FLATPARTS, K_FLPTOLERANCE, 0.1, m_MainWindow.GetIniFile())
      EgtCreateAdjustFlatParts(nType, dToler)
      ' Se prevista gestione colore->angolo di fianco
      If GetPrivateProfileInt(S_COLORTOSIDEANG, K_CTSA_ENABLE, 0, m_MainWindow.GetIniFile()) <> 0 Then
         SideAngle.ColorToSideAngle(ImportScene.GetCtx())
      End If
      ' Se prevista gestione colore->incisioni
      If GetPrivateProfileInt(S_COLORTOENGRAVE, K_CTE_ENABLE, 0, m_MainWindow.GetIniFile()) <> 0 Then
         Engrave.ColorToEngrave(ImportScene.GetCtx())
      End If
      ' gestico il colore degli elementi da importare (devono avere una regione definita!
      ColorRegion(ImportScene.GetCtx())
      ' Eseguo zoom
      ImportScene.ZoomAll()
      ' disabilito bottoni UseLayer e UseRegion, abilito bottoni Reset e Insert
      UseLayerBtn.IsEnabled = False
      UseClosedCurveBtn.IsEnabled = False
      UseRegionBtn.IsEnabled = False
      ResetBtn.IsEnabled = True
      OkBtn.IsEnabled = True
      ' abilito bottone angoli su lati esterni
      SideAngleBtn.IsEnabled = m_MainWindow.m_DrawPageUC.bEnableSideAngle
      FiloTopBtn.IsEnabled = m_MainWindow.m_CurrentMachine.bMilling
      DripCutBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                             Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripSaw)
      DripDrillBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                               Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripDrill)
   End Sub

   Private Function FilterNge(bEraseNames As Boolean) As Boolean
      ' Rimuovo eventuali gruppi con livello System
      Dim nId As Integer = EgtGetFirstGroupInGroup(GDB_ID.ROOT)
      While nId <> GDB_ID.NULL
         ' Recupero il prossimo gruppo
         Dim nNextId = EgtGetNextGroup(nId)
         ' Verifico il livello e se necessario cancello
         Dim nLevel As Integer = GDB_LV.USER
         EgtGetLevel(nId, nLevel)
         If nLevel = GDB_LV.SYSTEM Then
            EgtErase(nId)
         End If
         ' Passo al prossimo gruppo
         nId = nNextId
      End While
      ' Processo i sottogruppi, se di livello System li rimuovo altrimenti se richiesto ne cancello il nome
      Dim nGrpId As Integer = EgtGetFirstGroupInGroup(GDB_ID.ROOT)
      While nGrpId <> GDB_ID.NULL
         ' Ciclo sui sottogruppi
         Dim nSubId As Integer = EgtGetFirstGroupInGroup(nGrpId)
         While nSubId <> GDB_ID.NULL
            ' Recupero il prossimo sottogruppo
            Dim nNextSubId = EgtGetNextGroup(nSubId)
            ' Verifico il livello, eventuale cancellazione o rimozione nome
            Dim nLevel As Integer = GDB_LV.USER
            EgtGetLevel(nSubId, nLevel)
            If nLevel = GDB_LV.SYSTEM Then
               EgtErase(nSubId)
            ElseIf bEraseNames Then
               EgtRemoveName(nSubId)
            End If
            nSubId = nNextSubId
         End While
         ' Passo al prossimo gruppo
         nGrpId = EgtGetNextGroup(nGrpId)
      End While
      Return True
   End Function

   Private Function ImportTrf(sPath As String) As Boolean
      ' Definizione variabili
      EgtLuaCreateGlobTable("TRF")
      EgtLuaSetGlobStringVar("TRF.FILE", sPath)
      ' Path script da eseguire
      Dim sLuaPath = m_MainWindow.GetTrfAutoDir() & "\TrfRead.lua"
      ' Esecuzione
      Dim nErr As Integer = 999
      If EgtLuaExecFile(sLuaPath) AndAlso
         EgtLuaCallFunction("TRF.Read") Then
         ' Verifica stato di errore
         EgtLuaGetGlobIntVar("TRF.ERR", nErr)
      End If
      If nErr <> 0 Then EgtOutLog("Error in TrfRead : " & nErr.ToString())
      EgtLuaResetGlobVar("TRF")
      ' Sistemazione layer
      EgtAdjustFlatParts()
      Return (nErr = 0)
   End Function

   Private Sub ResetBtn_Click(sender As Object, e As RoutedEventArgs) Handles ResetBtn.Click
      ' Ricarico file corrente
      LoadCurrFile()
   End Sub

   Private Sub mmBtn_Click(sender As Object, e As RoutedEventArgs) Handles mmBtn.Click, inchBtn.Click
      ' Dal bottone premuto imposto l'unità di misura
      Dim bMM As Boolean = False
      If mmBtn.IsChecked() Then bMM = True
      ' Se stato cambiato, salvo e ricarico file
      If m_bMM <> bMM Then
         m_bMM = bMM
         LoadCurrFile()
      End If
   End Sub

   Private Sub OrderListBtn_Click(sender As Object, e As RoutedEventArgs) Handles OrderListBtn.Click
      Dim DlgOrderList As New CompoCsvData( m_MainWindow)
      DlgOrderList.SetData( m_sOrder, m_sList)
      If DlgOrderList.ShowDialog() Then
         DlgOrderList.GetData( m_sOrder, m_sList)
      End If
   End Sub

   Private Sub OkBtn_Click(sender As Object, e As RoutedEventArgs) Handles OkBtn.Click
      m_SceneButtons.MeasureBtn.IsChecked = False
      ' Se import per pezzi piatti
      If m_MainWindow.m_PrevActivePage = MainWindow.Pages.CadCut Then
         ' Eseguo importazione pezzi piatti
         LoadFlatParts()
      ' altrimenti import per cornici
      Else
         LoadFrame()
      End If
      ' Istruzioni per chiudere ImportPageUC e aprire CadCutPageUC
      m_MainWindow.MainWindowGrid.Children.Remove(m_MainWindow.m_ImportPageUC)
      m_MainWindow.MainWindowGrid.Children.Add(m_MainWindow.m_CurrentProjectPageUC)
      m_MainWindow.m_ActivePage = m_MainWindow.m_PrevActivePage
   End Sub

   Private Sub LoadFlatParts()
      ' Cancello regioni di selezione dai pezzi
      Dim PartId As Integer = EgtGetFirstPart()
      While PartId <> GDB_ID.NULL
         EgtErase(EgtGetFirstNameInGroup(PartId, SELECT_REGION_LAYER))
         PartId = EgtGetNextPart(PartId)
      End While

      ' identificativo univoico del gruppo di pezzi, se più di un pezzo
      Dim sGUICode As New List(Of String)

      ' Scrivo testi per nesting
      SideAngle.WriteSideAngleForNest(ImportScene.GetCtx())
      ' Imposto riferimento sul centro geometrico di ogni pezzo
      VeinMatching.SetRefOnAllParts(ImportScene.GetCtx())
      ' Eventuale pulizia VeinMatching
      VeinMatching.Clear()
      ' Salvo tutti i pezzi in un file temporaneo
      Dim sTmpFile As String = m_MainWindow.GetTempDir() & "\FlatPart" & ".Nge"
      If Not EgtSaveFile(sTmpFile, NGE.BIN) Then Return

      ' Determino numero ripetizioni
      Dim nRepeat = 1
      StringToInt(PartNumTxBx.Text, nRepeat)
      nRepeat = Math.Min(Math.Max(1, nRepeat), 50)
      ' creo il riferimento
      If nRepeat > 1 Then
         ' per ogni pezze del file DXF creo un gruppo
         Dim nIdTemp As Integer = EgtGetFirstPart()
         While nIdTemp <> GDB_ID.NULL
            Dim sPreGuid As String = CreatePreGuidCode(nIdTemp)
            sGUICode.Add(sPreGuid & System.Guid.NewGuid.ToString)
            nIdTemp = EgtGetNextPart(nIdTemp)
         End While
      End If

      ' Passo al contesto principale
      EgtSetCurrentContext(m_MainWindow.m_CurrentProjectPageUC.CurrentProjectScene.GetCtx())
      ' Recupero flag per inserimento diretto in grezzo (altrimenti in parcheggio)
      Dim bDirect As Boolean = (GetPrivateProfileInt(S_NEST, K_DIRECT, 0, m_MainWindow.GetIniFile()) <> 0)
      ' Elimino eventuali precedenti pezzi vuoti
      EgtEraseEmptyParts()

      ' Inserisco i pezzi nell'ambiente principale e recupero Id primo pezzo inserito
      Dim nFirstId As Integer = EgtGetLastPart()
      For nInd As Integer = 1 To nRepeat
         Dim nFirst2Id As Integer = EgtGetLastPart()
         EgtInsertFile(sTmpFile)

         Dim FirstOfImport As Integer = EgtGetNextPart(nFirst2Id)
         Dim Index As Integer = 1
         While FirstOfImport <> GDB_ID.NULL And Index <= sGUICode.Count
            If Not String.IsNullOrEmpty(sGUICode(Index - 1)) Then
               EgtSetInfo(FirstOfImport, INFO_REFGROUP, sGUICode(Index - 1))
               Index += 1
            Else
               Exit While
            End If
            FirstOfImport = EgtGetNextPart(FirstOfImport)
         End While

         nFirst2Id = If(nFirst2Id <> GDB_ID.NULL, EgtGetNextPart(nFirst2Id), EgtGetFirstPart())
         ' Eventuale inserimento pezzi in VeinMatching
         VeinMatching.AddParts(sTmpFile, nFirst2Id)
      Next
      nFirstId = If(nFirstId <> GDB_ID.NULL, EgtGetNextPart(nFirstId), EgtGetFirstPart())

      ' Cancello il file
      If My.Computer.FileSystem.FileExists(sTmpFile) Then
         My.Computer.FileSystem.DeleteFile(sTmpFile)
      End If
      ' Calcolo l'area dei pezzi inseriti
      Dim dNewArea As Double = 0
      Dim nId As Integer = nFirstId
      While nId <> GDB_ID.NULL
         dNewArea += GeomCalc.GetPartArea(nId)
         ' Passo al pezzo successivo
         nId = EgtGetNextPart(nId)
      End While
      ' Nascondo tutti i pezzi inseriti (per evitare interferenze con pezzi in fase di parcheggio)
      nId = nFirstId
      While nId <> GDB_ID.NULL
         EgtSetStatus(nId, GDB_ST.OFF)
         ' Passo al pezzo successivo
         nId = EgtGetNextPart(nId)
      End While
      ' Ciclo sui pezzi inseriti
      nId = nFirstId
      While nId <> GDB_ID.NULL
         ' lo salvo come Id originale
         EgtSetInfo(nId, KEY_ORI_ID, nId)
         ' 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)
         ' Se file origine Dxf o Nge
         If m_nFileType = FT.DXF Or m_nFileType = FT.NGE Then
            ' Eventuale testo per indicare il sopra
            If TopBtn.IsChecked() Then
               Utility.AddTopToPartRegion(nRegId)
            End If
            ' Se richiesti, inserisco dati Ordine, Distinta, Nome, Origine
            If m_bEnableOrderList Then
               ' Cerco il nome del pezzo
               Dim sName As String = ""
               EgtGetName(nId, sName)
               ' Recupero il box del pezzo
               Dim b3Reg As New BBox3d : EgtGetBBox(nRegId, GDB_BB.IGNORE_TEXT + GDB_BB.IGNORE_DIM, b3Reg)
               ' Aggiungo info equivalenti a CSV
               EgtSetInfo(nId, INFO_CSV_PART, sName)
               EgtSetInfo(nId, INFO_CSV_ORD, m_sOrder)
               EgtSetInfo(nId, INFO_CSV_DIST, m_sList)
               EgtSetInfo(nId, INFO_CSV_MAT, m_MainWindow.m_CurrentMachine.CurrMat.sName)
               EgtSetInfo(nId, INFO_CSV_V1, DoubleToString(b3Reg.DimX(), 1))
               EgtSetInfo(nId, INFO_CSV_V2, DoubleToString(b3Reg.DimY(), 1))
            End If
         End If
         ' Imposto colore testi
         Utility.SetTextColor(nRegId)
         ' Imposto path di provenienza
         EgtSetInfo(nId, INFO_SOU_PATH, IO.Path.Combine(m_sCurrDir, m_sCurrFile))
         ' Inserisco in parcheggio
         m_MainWindow.m_CadCutPageUC.m_NestPage.StoreOnePart(nId, True)
         ' Recupero Id di pezzo successivo
         Dim nNextId As Integer = EgtGetNextPart(nId)
         ' Se richiesto posizionamento diretto, lo eseguo
         If bDirect Then
            If m_MainWindow.m_CadCutPageUC.m_NestPage.InsertOnePart(nId) Then
               ' Eventuale notifica al VeinMatching
               VeinMatching.OnInsertPartInRaw(nId)
            End If
         End If
         ' Passo al pezzo successivo
         nId = nNextId
      End While
      ' Eventuale aggiornamento VeinMatching
      VeinMatching.ZoomAll()
      ' Aggiorno Aree totale e da lavorare dei pezzi
      m_MainWindow.m_CurrentProjectPageUC.UpdateTotalArea(dNewArea)
      m_MainWindow.m_CurrentProjectPageUC.UpdateToProduceArea()
      m_MainWindow.m_CurrentProjectPageUC.ShowAreas()
      ' Aggiorno ambiente principale
      EgtZoom(ZM.ALL)
   End Sub

   Private Sub LoadFrame()
      ' recupero il primo layer del primo pezzo
      Dim nLayerId As Integer = EgtGetFirstLayer(EgtGetFirstPart())
      If nLayerId = GDB_ID.NULL Then Return
      ' Lo esporto in un file temporaneo
      Dim sTmpFile As String = m_MainWindow.GetTempDir() & "\Frame.Nge"
      If Not EgtSaveObjToFile(nLayerId, sTmpFile, NGE.BIN) Then Return
      ' Passo al contesto principale
      EgtSetCurrentContext(m_MainWindow.m_CurrentProjectPageUC.CurrentProjectScene.GetCtx())
      ' Inserisco il pezzo
      If Not My.Computer.FileSystem.FileExists(sTmpFile) Then Return
      EgtInsertFile(sTmpFile)
      ' Ne recupero l'Id
      Dim nPartId As Integer = EgtGetLastPart()
      ' Creo la cornice
      m_MainWindow.m_FrameCutPageUC.CreateFrame(nPartId)
      ' Ricalcolo lavorazioni
      AddFrameMachinings(m_MainWindow.m_FrameCutPageUC.m_FrameMachiningUC.m_dStartTrim, m_MainWindow.m_FrameCutPageUC.m_FrameMachiningUC.m_dEndTrim)
      ' Cancello il file
      My.Computer.FileSystem.DeleteFile(sTmpFile)
   End Sub

   Private Sub ExitBtn_Click(sender As Object, e As RoutedEventArgs) Handles ExitBtn.Click
      m_SceneButtons.MeasureBtn.IsChecked = False
      ' Istruzioni per chiudere ImportPageUC e aprire CadCutPageUC
      m_MainWindow.MainWindowGrid.Children.Remove(m_MainWindow.m_ImportPageUC)
      m_MainWindow.MainWindowGrid.Children.Add(m_MainWindow.m_CurrentProjectPageUC)
      m_MainWindow.m_ActivePage = m_MainWindow.m_PrevActivePage
   End Sub

   Private Sub ImportPage_Unloaded(sender As Object, e As RoutedEventArgs)
      ' Salvo direttorio corrente
      WritePrivateProfileString(S_FLATPARTS, K_FLPCURRDIR, m_sCurrDir, m_MainWindow.GetIniFile())
      ' Tolgo pagina inclinazioni/gocciolatoi se attiva
      If SideAngleBtn.IsChecked() Or DripCutBtn.IsChecked() Then
         FilePathTxBl.Visibility = Windows.Visibility.Visible
         FileListBox.Visibility = Windows.Visibility.Visible
         LeftGrid.Children.Remove(m_SideAngleUC)
         If SideAngleBtn.IsChecked() Then
            SideAngleBtn.IsChecked = False
         Else
            DripCutBtn.IsChecked() = False
         End If
      ' Tolgo pagina fori da sotto se attiva
      ElseIf DripDrillBtn.IsChecked() Then
         FilePathTxBl.Visibility = Windows.Visibility.Visible
         FileListBox.Visibility = Windows.Visibility.Visible
         LeftGrid.Children.Remove(m_UnderDrillUC)
         DripDrillBtn.IsChecked() = False
      ' Tolgo pagina Filo Top se attiva
      ElseIf FiloTopBtn.IsChecked() Then
         FilePathTxBl.Visibility = Windows.Visibility.Visible
         FileListBox.Visibility = Windows.Visibility.Visible
         LeftGrid.Children.Remove(m_FiloTopUC)
         FiloTopBtn.IsChecked() = False
      End If
      ' Pulisco area messaggi
      MessageTxBx.Text = ""
      MessageBrd.Background = Brushes.Transparent
   End Sub

   Private Sub SideAngleBtn_Click(sender As Object, e As RoutedEventArgs) Handles SideAngleBtn.Click
      If SideAngleBtn.IsChecked() Then
         ' Aggiungo regioni per percorsi interni
         AdjustSelectRegions()
         ' Dichiaro nessuna selezione
         m_nSelectedPart = GDB_ID.NULL
         m_nSelectedLayer = GDB_ID.NULL
         ' Imposto modalità sideangle
         m_SideAngleUC.m_Mode = SideAngleUC.ModeOpt.SIDEANGLE
         LeftGrid.Children.Add(m_SideAngleUC)
         FilePathTxBl.Visibility = Windows.Visibility.Hidden
         FileListBox.Visibility = Windows.Visibility.Hidden
         ' Disabilito FiloTopBtn, DripCutBtn, DripDrillBtn e unità di misura
         FiloTopBtn.IsEnabled = False
         DripCutBtn.IsEnabled = False
         DripDrillBtn.IsEnabled = False
         mmBtn.IsEnabled = False
         inchBtn.IsEnabled = False
         ' Disabilito bottone reset
         ResetBtn.IsEnabled = False
         ' Messaggio di selezione da effettuare
         MessageTxBx.Text = EgtMsg(MSG_DRAWPAGEUC + 6)   ' Selezionare un contorno
         MessageBrd.Background = Application.Current.FindResource("OmagCut_Green")
      Else
         ' Rimuovo regioni per percorsi interni
         RemoveSelectRegions()
         FilePathTxBl.Visibility = Windows.Visibility.Visible
         FileListBox.Visibility = Windows.Visibility.Visible
         LeftGrid.Children.Remove(m_SideAngleUC)
         ' Deseleziono eventuali pezzi rimasti selezionati
         m_nSelectedPart = GDB_ID.NULL
         m_nSelectedLayer = GDB_ID.NULL
         EgtDeselectAll()
         ' Riabilito FiloTopBtn, DripCutBtn, DripDrillBtn e unità di misura
         FiloTopBtn.IsEnabled = m_MainWindow.m_CurrentMachine.bMilling
         DripCutBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                                Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripSaw)
         DripDrillBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                                  Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripDrill)
         mmBtn.IsEnabled = True
         inchBtn.IsEnabled = True
         ' Elimino scritte angoli per input e inserisco quelle definitive
         SideAngle.WriteSideAngleForNest(ImportScene.GetCtx())
         ' Riabilito bottone reset
         ResetBtn.IsEnabled = True
         ' Pulisco area messaggi
         MessageTxBx.Text = ""
         MessageBrd.Background = Brushes.Transparent
      End If
      EgtZoom(ZM.ALL)
   End Sub

   Private Sub DripCutBtn_Click(sender As Object, e As RoutedEventArgs) Handles DripCutBtn.Click
      If DripCutBtn.IsChecked() Then
         ' Dichiaro nessuna selezione
         m_nSelectedPart = GDB_ID.NULL
         m_nSelectedLayer = GDB_ID.NULL
         ' Imposto modalità drip
         m_SideAngleUC.m_Mode = SideAngleUC.ModeOpt.DRIP
         LeftGrid.Children.Add(m_SideAngleUC)
         FilePathTxBl.Visibility = Windows.Visibility.Hidden
         FileListBox.Visibility = Windows.Visibility.Hidden
         ' Disabilito SideAngleBtn,FiloTop,  DripDrillBtn e unità di misura
         SideAngleBtn.IsEnabled = False
         FiloTopBtn.IsEnabled = False
         DripDrillBtn.IsEnabled = False
         mmBtn.IsEnabled = False
         inchBtn.IsEnabled = False
         ' Disabilito bottone reset
         ResetBtn.IsEnabled = False
         ' Messaggio di selezione da effettuare
         MessageTxBx.Text = EgtMsg(MSG_DRAWPAGEUC + 6)   ' Selezionare un contorno
         MessageBrd.Background = Application.Current.FindResource("OmagCut_Green")
      Else
         FilePathTxBl.Visibility = Windows.Visibility.Visible
         FileListBox.Visibility = Windows.Visibility.Visible
         LeftGrid.Children.Remove(m_SideAngleUC)
         ' Deseleziono eventuali pezzi rimasti selezionati
         m_nSelectedPart = GDB_ID.NULL
         m_nSelectedLayer = GDB_ID.NULL
         EgtDeselectAll()
         ' Riabilito SideAngleBtn, FiloTop, DripDrillBtn e unità di misura
         SideAngleBtn.IsEnabled = m_MainWindow.m_DrawPageUC.bEnableSideAngle
         FiloTopBtn.IsEnabled = m_MainWindow.m_CurrentMachine.bMilling
         DripDrillBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                                  Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripDrill)
         mmBtn.IsEnabled = True
         inchBtn.IsEnabled = True
         ' Elimino scritte angoli per input e inserisco quelle definitive
         SideAngle.WriteSideAngleForNest(ImportScene.GetCtx())
         ' Ricavo nome pezzo selezionato
         Dim Part1 As Integer = m_MainWindow.m_ImportPageUC.m_nSelectedPart
         EgtErase(EgtGetFirstNameInGroup(Part1, SIDE_ANGLE_LAYER))
         ' Riabilito bottone reset
         ResetBtn.IsEnabled = True
         ' Pulisco area messaggi
         MessageTxBx.Text = ""
         MessageBrd.Background = Brushes.Transparent
      End If
      EgtZoom(ZM.ALL)
   End Sub

   Private Sub DripDrillBtn_Click(sender As Object, e As RoutedEventArgs) Handles DripDrillBtn.Click
      If DripDrillBtn.IsChecked() Then
         ' Aggiungo regioni di selezione per percorsi interni
         AdjustSelectRegions()
         ' Imposto modalità fori da sotto
         LeftGrid.Children.Add(m_UnderDrillUC)
         FilePathTxBl.Visibility = Windows.Visibility.Hidden
         FileListBox.Visibility = Windows.Visibility.Hidden
         ' Disabilito SideAngleBtn, FiloTop, DripCutBtn e unità di misura
         SideAngleBtn.IsEnabled = False
         FiloTopBtn.IsEnabled = False
         DripCutBtn.IsEnabled = False
         mmBtn.IsEnabled = False
         inchBtn.IsEnabled = False
         ' Disabilito bottone reset
         ResetBtn.IsEnabled = False
         ' Messaggio di selezione da effettuare
         MessageTxBx.Text = EgtMsg(MSG_DRAWPAGEUC + 15)   ' Selezionare uno o più fori
         MessageBrd.Background = Application.Current.FindResource("OmagCut_Green")
      Else
         ' Rimuovo regioni per percorsi interni
         RemoveSelectRegions()
         FilePathTxBl.Visibility = Windows.Visibility.Visible
         FileListBox.Visibility = Windows.Visibility.Visible
         LeftGrid.Children.Remove(m_UnderDrillUC)
         ' Deseleziono eventuali pezzi rimasti selezionati
         m_nSelectedPart = GDB_ID.NULL
         m_nSelectedLayer = GDB_ID.NULL
         EgtDeselectAll()
         ' Riabilito SideAngleBtn, FiloTop, DripCutBtn e unità di misura
         SideAngleBtn.IsEnabled = m_MainWindow.m_DrawPageUC.bEnableSideAngle
         FiloTopBtn.IsEnabled = m_MainWindow.m_CurrentMachine.bMilling
         DripCutBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                                Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripSaw)
         mmBtn.IsEnabled = True
         inchBtn.IsEnabled = True
         ' Riabilito bottone reset
         ResetBtn.IsEnabled = True
         ' Pulisco area messaggi
         MessageTxBx.Text = ""
         MessageBrd.Background = Brushes.Transparent
      End If
      EgtZoom(ZM.ALL)
   End Sub

   Private Sub FiloTopBtn_Click(sender As Object, e As RoutedEventArgs) Handles FiloTopBtn.Click
      If FiloTopBtn.IsChecked() Then
         ' Aggiungo regioni per percorsi interni
         AdjustSelectRegions()
         ' Dichiaro nessuna selezione
         m_nSelectedPart = GDB_ID.NULL
         m_nSelectedLayer = GDB_ID.NULL
         ' Imposto modalità FiloTop
         LeftGrid.Children.Add(m_FiloTopUC)
         FilePathTxBl.Visibility = Windows.Visibility.Hidden
         FileListBox.Visibility = Windows.Visibility.Hidden
         ' Disabilito SideAngleBtn, DripCutBtn, DripDrillBtn e unità di misura
         SideAngleBtn.IsEnabled = False
         DripCutBtn.IsEnabled = False
         DripDrillBtn.IsEnabled = False
         mmBtn.IsEnabled = False
         inchBtn.IsEnabled = False
         ' Disabilito bottone reset
         ResetBtn.IsEnabled = False
         ' Messaggio di selezione da effettuare
         MessageTxBx.Text = EgtMsg(MSG_DRAWPAGEUC + 6)   ' Selezionare un contorno interno
         MessageBrd.Background = Application.Current.FindResource("OmagCut_Green")
      Else
         ' Rimuovo regioni per percorsi interni
         RemoveSelectRegions()
         FilePathTxBl.Visibility = Windows.Visibility.Visible
         FileListBox.Visibility = Windows.Visibility.Visible
         LeftGrid.Children.Remove(m_FiloTopUC)
         ' Deseleziono eventuali pezzi rimasti selezionati
         m_nSelectedPart = GDB_ID.NULL
         m_nSelectedLayer = GDB_ID.NULL
         EgtDeselectAll()
         ' Riabilito SideAngleBtn, DripCutBtn, DripDrillBtn e unità di misura
         SideAngleBtn.IsEnabled = m_MainWindow.m_DrawPageUC.bEnableSideAngle
         DripCutBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                                Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripSaw)
         DripDrillBtn.IsEnabled = m_MainWindow.GetKeyOption(MainWindow.KEY_OPT.UNDER_CUT) And
                                  Not String.IsNullOrWhiteSpace(m_MainWindow.m_CurrentMachine.sCurrDripDrill)
         mmBtn.IsEnabled = True
         inchBtn.IsEnabled = True
         ' Riabilito bottone reset
         ResetBtn.IsEnabled = True
         ' Pulisco area messaggi
         MessageTxBx.Text = ""
         MessageBrd.Background = Brushes.Transparent
      End If
      EgtZoom(ZM.ALL)
   End Sub

   Private Function AdjustSelectRegions() As Boolean
      ' Ciclo sui pezzi
      Dim nPartId As Integer = EgtGetFirstPart()
      While nPartId <> GDB_ID.NULL
         ' Se layer con regioni di selezione dei percorsi interni non definito ...
         Dim nSelRegId As Integer = EgtGetFirstNameInGroup(nPartId, SELECT_REGION_LAYER)
         If nSelRegId = GDB_ID.NULL Then
            ' Creo layer per regioni di selezione
            nSelRegId = EgtCreateGroup(nPartId)
            EgtSetName(nSelRegId, SELECT_REGION_LAYER)
            RegionFromGroup(nPartId, nSelRegId, NAME_INLOOP)
            RegionFromGroup(nPartId, nSelRegId, NAME_UNDERDRILL)
         End If
         ' Passo al pezzo successivo
         nPartId = EgtGetNextPart(nPartId)
      End While
      Return True
   End Function

   Private Function RemoveSelectRegions() As Boolean
      ' Ciclo sui pezzi
      Dim nPartId As Integer = EgtGetFirstPart()
      While nPartId <> GDB_ID.NULL
         ' Se layer con regioni di selezione dei percorsi interni non definito ...
         Dim nSelRegId As Integer = EgtGetFirstNameInGroup(nPartId, SELECT_REGION_LAYER)
         EgtErase(nSelRegId)
         ' Passo al pezzo successivo
         nPartId = EgtGetNextPart(nPartId)
      End While
      Return True
   End Function

   Private Sub RegionFromGroup(nPartId As Integer, nSelRegId As Integer, GroupName As String)
      ' Ciclo sui percorsi interni chiusi
      Dim nIntLayId As Integer = EgtGetFirstNameInGroup(nPartId, GroupName)
      While nIntLayId <> GDB_ID.NULL
         ' Recupero gli identificatori delle curve che formano il loop
         Dim vCrvId As New List(Of Integer)
         Dim nCrvId As Integer = EgtGetFirstInGroup(nIntLayId)
         While nCrvId <> GDB_ID.NULL
            Dim nType As Integer = EgtGetType(nCrvId)
            If SideAngleBtn.IsChecked() OrElse FiloTopBtn.IsChecked() Then
               If nType = GDB_TY.CRV_LINE Or nType = GDB_TY.CRV_ARC Or nType = GDB_TY.CRV_COMPO Then
                  vCrvId.Add(nCrvId)
               End If
            ElseIf DripDrillBtn.IsChecked
               if nType = GDB_TY.CRV_ARC
                  vCrvId.Add(nCrvId)
               End If
            End If
            nCrvId = EgtGetNext(nCrvId)
         End While
         ' Creo curva chiusa
         Dim nLoopId As Integer = EgtCreateCurveCompoByReorder(nSelRegId, vCrvId.Count(), vCrvId.ToArray(), Point3d.ORIG(), False)
         EgtInvertCurve(nLoopId)
         ' Creo superficie
         Dim nRegId As Integer = EgtCreateSurfFlatRegion(nSelRegId, nLoopId)
         EgtSetName(nRegId, nIntLayId.ToString())
         EgtSetInfo(nRegId, "ID", nIntLayId)
         EgtSetColor(nRegId, New Color3d(0, 255, 0, 25))
         EgtErase(nLoopId)
         If GroupName = NAME_UNDERDRILL Then
            EgtSelectObj(nRegId)
            EgtSelectObj(nIntLayId)
         End If
         ' Passo al successivo layer interno
         nIntLayId = EgtGetNextName(nIntLayId, GroupName)
      End While
   End Sub

   Private Sub Cad2dBtn_Click(sender As Object, e As RoutedEventArgs) Handles Cad2dBtn.Click

      Dim ProcsCad2d As Process() = Process.GetProcessesByName( m_sCad2dName)
      If ProcsCad2d.Length() > 0 Then
         ShowWindow( ProcsCad2d(0).MainWindowHandle, 3)
      Else
         Process.Start( m_sCad2dPath)
      End If

   End Sub

End Class

Public Class IconListBoxItem

    Private m_iPictureID As Integer
    Private m_sName As String

    Public Property PictureID() As Integer
        Get
            Return m_iPictureID
        End Get
        Set(value As Integer)
            m_iPictureID = value
        End Set
    End Property

    Public Property Name() As String
        Get
            Return m_sName
        End Get
        Set(value As String)
            m_sName = value
        End Set
    End Property

    Public ReadOnly Property PictureString() As String
        Get
            Return "/Resources/ImportPageListBoxImages/" + PictureID.ToString() + ".png"
        End Get
    End Property

    Sub New()
        Me.Name = String.Empty
        Me.PictureID = 0
    End Sub

    Sub New(Name As String, PictureID As Integer)
        Me.Name = Name
        Me.PictureID = PictureID
    End Sub


End Class