Imports EgtUILib
Imports EgtPHOTOLib
Imports System.IO

Public Class ScrapsWD
   ' Riferimento alla MainWindow
   Private m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
   Private m_refProjectMgrUC As ProjectMgrUC

   Private m_ScrapList As New List(Of Scrap)
   Private m_CurrScrapId As Integer = GDB_ID.NULL
   Private m_CurrScrapState As Integer = 2
   Private m_sDatabaseId As String = ""

   Private Sub Initalized()
      ' resetto eventuali errori mostrati nella pagina
      m_MainWindow.m_CurrentProjectPageUC.ClearMessage()

      ' inserisco il titolo della pagina aperta
      TitleTxBl.Content = "Scraps List"
      ScrapsListBox.ItemsSource = m_ScrapList
      ' definzione posizione finetra
      Me.Left = 25
      Me.Top = 25
   End Sub

   Public Sub New(Owner As Window, LocalProjectMgrUC As ProjectMgrUC, MyScrapList As List(Of Scrap))
      Me.Owner = Owner
      InitializeComponent()
      m_ScrapList = MyScrapList
      m_refProjectMgrUC = LocalProjectMgrUC
      Initalized()
   End Sub


   ' visualizzo la fase del pezzo selezionato
   Private Sub ScrapListBox_PreviewMouseUp(sender As Object, e As MouseButtonEventArgs) Handles ScrapsListBox.PreviewMouseUp
      Dim vItems As Scrap = ScrapsListBox.SelectedItems(0)
      ' elimino l'utimo selzione
      EgtResetMark(m_CurrScrapId)
      EgtDeselectObj(m_CurrScrapId)
      ' ricerco il grezzo associato a questo Id
      Dim nRawId As Integer = EgtGetFirstRawPart()
      While nRawId <> GDB_ID.NULL
         If nRawId = vItems.IdRaw Then
            m_CurrScrapId = nRawId
            m_CurrScrapState = vItems.nState
            If m_CurrScrapState = 2 Then
               EgtGetInfo(nRawId, K_DATABASEID, m_sDatabaseId)
            Else
               m_sDatabaseId = String.Empty
            End If
            Dim nCurrRawPhase As Integer = 0
            ' recupero la fase del grezzo corrente
            EgtGetInfo(nRawId, "Ph", nCurrRawPhase)
            If nCurrRawPhase <> 0 Then
               ' evidenzio lo sfrido selezionato all'interno della fase
               EgtSetCurrPhase(nCurrRawPhase)
               EgtSetMark(m_CurrScrapId)
               EgtSelectObj(m_CurrScrapId)
               EgtDraw()
               Return
            End If
         End If
         nRawId = EgtGetNextRawPart(nRawId)
      End While

   End Sub

   Private Sub OkBtn_Click() Handles OkBtn.Click
      If m_CurrScrapId = GDB_ID.NULL Then Return
      ' creo una copia dell'immagine attuale (fotocamera 1)
      Dim sImage As String = String.Empty
      Dim sInfo As String = String.Empty
      GetPrivateProfileString(S_CAMERA, K_CAM_IMAGE, "", sImage, m_MainWindow.GetIniFile())
      GetPrivateProfileString(S_CAMERA, K_CAM_INFO, "", sInfo, m_MainWindow.GetIniFile())
      ' recupero dalla libreria il percoso del database
      Dim sPhotoDir As String = String.Empty
      EgtPHOTOLib.GetPhotoDir(sPhotoDir)
      ' recupero l'ora corrente
      Dim sDate As String = Date.Now.ToString
      sDate = sDate.Replace("/", "_")
      sDate = sDate.Replace(" ", "_")
      sDate = sDate.Replace(":", "_")
      Dim sNewPath As String = sPhotoDir & "\Scrap_" & sDate
      Try
         File.Copy(sImage, sNewPath & ".jpg", False)
         File.Copy(sInfo, sNewPath & ".txt", False)
      Catch ex As Exception
         EgtOutLog(ex.Message.ToString)
      End Try

      ' se non esiste la classe StatusBar allora provo ad inizializzarla...
      If IsNothing(EgtWPFLib5.LibMap.refStatusBarVM) Then
         Dim objStatusBarVM As New EgtWPFLib5.StatusBarVM
      End If
      ' salvo il contesto corrente del programma
      Dim nCurrentContetxt As Integer = EgtGetCurrentContext()
      ' costruisco l'elenco ordinato dei punti che reppresentano il contorno del grezzo da salvare
      Dim ContornScrapList As New List(Of Point3d)

      Dim RefId As New Frame3d
      Dim nRawSolidId As Integer = EgtGetFirstNameInGroup(m_CurrScrapId, "RawSolid")
      EgtGetTextureFrame(nRawSolidId, nRawSolidId, RefId)
      Dim nCurveCompoId As Integer = EgtGetFirstNameInGroup(m_CurrScrapId, "RawOutline")
      Dim dStart As Double = 0
      Dim dEnd As Double = 0
      EgtCurveDomain(nCurveCompoId, dStart, dEnd)
      Dim ptCurrPoint As Point3d
      For dU As Integer = dStart To dEnd - 1
         EgtAtParamPoint(nCurveCompoId, dU, m_CurrScrapId, ptCurrPoint)
         ptCurrPoint.z = 0
         ptCurrPoint.ToLoc(RefId)
         ContornScrapList.Add(ptCurrPoint)
      Next

      MainData.SetPreviousContext(nCurrentContetxt)

      'If Not IsNothing(MainData.ContextSTONELib) Or MainData.ContextSTONELib <> 0 Then
      'If MainData.ContextSTONELib <> 0 Then
      '   EgtSetCurrentContext(MainData.ContextSTONELib)
      'End If

      ' inizializzo PojectSlabV pechè si occupa di inizializzare le pagine Detail e Option 
      Dim MyProjectSlab As New EgtPHOTOLib.ProjectSlabV
      ' ACCELERARE il processo di creazione di questo oggetto!
      MyProjectSlab.DataContext = New EgtPHOTOLib.ProjectSlabVM
      ' per ogni creazione della nuova pagina viene creata una nuova scena, ma non viene eliminata
      Dim refProjectVMSceneContext As Integer = EgtGetCurrentContext()

      ' apro la finestra OmagPHOTO (passo il nome del file come copia dell'originale)
      If ContornScrapList.Count > 2 Then
         Dim MyOmagPhotoWD As New OmagPhotoWD(sNewPath & ".jpg", ContornScrapList, m_MainWindow, m_CurrScrapState, m_sDatabaseId)
         OmagPhotoWD.m_IsAdded = False
         OmagPhotoWD.m_sDtBsId = String.Empty
         OmagPhotoWD.m_IsDeleted = False
         MyOmagPhotoWD.ShowDialog()
      Else
         m_MainWindow.m_CurrentProjectPageUC.ClearMessage()
         m_MainWindow.m_CurrentProjectPageUC.SetErrorMessage("Error loading contour scrap")
      End If

      ' ripristino il contesto corrente dell'immagine
      EgtSetCurrentContext(EgtPHOTOLib.MainData.PreviousContext)
      ' se l'inserimento è andatoa buon fine allora procedo a notificarlo
      If OmagPhotoWD.m_IsAdded AndAlso Not String.IsNullOrEmpty(OmagPhotoWD.m_sDtBsId) Then
         EgtSetInfo(m_CurrScrapId, K_ISNEWSCRAPS, 2)
         EgtSetInfo(m_CurrScrapId, K_DATABASEID, OmagPhotoWD.m_sDtBsId)
      Else
         ' se è stato eliminato dal DB allora aggiorno la lista dei grezzi
         If OmagPhotoWD.m_IsDeleted Then
            EgtSetInfo(m_CurrScrapId, K_ISNEWSCRAPS, 1)
            EgtRemoveInfo(m_CurrScrapId, K_DATABASEID)
         End If
         Try
            File.Delete(sNewPath & ".jpg")
            File.Delete(sNewPath & ".txt")
         Catch ex As Exception
            EgtOutLog(ex.Message.ToString)
         End Try
      End If

      '----------------INIZIO ELIMINAZIONE contesti generati da OmagPHOTOLib per la visualizzazione delle Texture
      EgtDeleteContext(EgtPHOTOLib.MainData.ContextSTONELib)
      EgtDeleteContext(refProjectVMSceneContext)
      '----------------  FINE ELIMINAZIONE contesti

      ' aggiorno la lista degli scrap
      m_refProjectMgrUC.UpDateScrapList(m_ScrapList)
      ScrapsListBox.ItemsSource = m_ScrapList
      ScrapsListBox.Items.Refresh()
   End Sub

   Private Sub ExitBtn_Click() Handles ExitBtn.Click
      ' resetto eventuali errori mostrati nella pagina
      m_MainWindow.m_CurrentProjectPageUC.ClearMessage()
      ' deseleziono l'oggetto corrente
      EgtResetMark(m_CurrScrapId)
      EgtDeselectObj(m_CurrScrapId)
      ' reimposto la fase iniziale
      EgtSetCurrPhase(1)
      EgtDraw()
      Me.Close()
   End Sub

End Class
