Imports System.Collections.ObjectModel
Imports System.IO
Imports EgtBEAMWALL.Core
Imports EgtBEAMWALL.Core.ConstBeam
Imports EgtUILib
Imports EgtWPFLib5

Public Class OpenProjectFileDialogVM
   Inherits Core.OpenProjectFileDialogVM

#Region "METHODS"

   Public Overrides Function Init(ProjectType As ProjectType, Optional CurrProjectList As List(Of ProjectFileVM) = Nothing, Optional GoToProd As Boolean = False) As Boolean?
      m_ProjectType = ProjectType
      ' carico colonne
      LoadColumns(ProjectType)
      NotifyPropertyChanged(NameOf(FilterTypeList))
      m_SelFilterType = m_FilterTypeList(0)
      ' carico lista progetti
      If IsNothing(CurrProjectList) OrElse CurrProjectList.Count = 0 Then
         SetFixedProjectList(False)
         RefreshProjectList(GoToProd)
      Else
         SetFixedProjectList(True)
         m_ProjectList = New ObservableCollection(Of ProjectFileVM)(CurrProjectList)
         NotifyPropertyChanged(NameOf(ProjectList))
      End If
      m_ProjectList_View = CollectionViewSource.GetDefaultView(m_ProjectList)
      m_ProjectList_View.Filter = AddressOf ProjectFilter
   End Function

   Public Overrides Sub RefreshProjectList(Optional GoToProd As Boolean = False)
      m_ProjectList.Clear()
      ' calcolo periodo e righe
      Dim dtStart As DateTime
      Dim dtEnd As DateTime
      Dim nRowQuantity As Integer = 20
      Select Case SelRowQuantity
         Case RowQuantities.FIFTY
            nRowQuantity = 50
         Case RowQuantities.HUNDRED
            nRowQuantity = 100
         Case RowQuantities.HUNDREDANDFIFTY
            nRowQuantity = 150
      End Select
      Select Case m_SelDayType
         Case DayTypes.LASTMONTH
            dtEnd = DateTime.Today + TimeSpan.FromDays(1)
            dtStart = dtEnd - TimeSpan.FromDays(30.5)
         Case DayTypes.LAST3MONTHS
            dtEnd = DateTime.Today + TimeSpan.FromDays(1)
            dtStart = dtEnd - TimeSpan.FromDays(30.5 * 3)
         Case DayTypes.LAST6MONTHS
            dtEnd = DateTime.Today + TimeSpan.FromDays(1)
            dtStart = dtEnd - TimeSpan.FromDays(30.5 * 6)
         Case DayTypes.PERIOD
            dtEnd = dtEndDate + TimeSpan.FromDays(1)
            dtStart = dtStartDate
      End Select
      ' leggo da db
      If m_ProjectType = ProjectType.PROJ Then
         Dim DbProjectList As New List(Of ProjFileM)
         ' CheckMe: lasciato come prima, anche NON attivi (cancellazione logica)
         If m_SelBTLDateType = BTLDateTypes.CREATEDATE Then
            DbProjectList = DbControllers.m_ProjController.GetLastDesc(dtStart, dtEnd, nRowQuantity, True)
         Else
            DbProjectList = DbControllers.m_ProjController.GetLastByExpDesc(dtStart, dtEnd, nRowQuantity, False)
         End If
         For Each Project In DbProjectList
            ' recupero path per verificare esista
            If IsNothing(Project.nProjId) OrElse Project.nProjId = 0 Then Continue For
            Dim sPath As String = Map.refMainWindowVM.MainWindowM.sProjsDir & "\" & Project.nProjId.ToString("0000") & "\" & Project.nProjId.ToString("0000") & ".nge"
            If File.Exists(sPath) Then
               m_ProjectList.Add(New ProjFileVM(Project))
            Else
               ' CheckMe impostata come cancellazione FISICA dal DB...
               DbControllers.m_ProjController.DeleteProj(Project.nProjId, False)
               EgtOutLog("Found project on Db without the folder and erased it! Proj number " & Project.nProjId.ToString("0000"))
            End If
         Next
      ElseIf m_ProjectType = ProjectType.PROD Then
         Dim DbProjectList As New List(Of ProdFileM)
         DbProjectList = DbControllers.m_ProdController.GetLastDesc(dtStart, dtEnd, nRowQuantity, True)
         If GoToProd Then
            For Each Project In DbProjectList
               ' recupero path per verificare esista
               If IsNothing(Project.nProdId) OrElse Project.nProdId = 0 Then Continue For
               Dim sPath As String = Map.refMainWindowVM.MainWindowM.sProdsDir & "\" & Project.nProdId.ToString("0000") & "\" & Project.nProdId.ToString("0000") & ".nge"
               If Project.sMachine = Map.refProjManagerVM.CurrProj.sMachine AndAlso
                  Project.nType = Map.refProjManagerVM.CurrProj.nType Then
                  If File.Exists(sPath) Then
                     m_ProjectList.Add(New ProdFileVM(Project))
                  Else
                     DbControllers.m_ProdController.DeleteProd(Project.nProdId, True)
                     EgtOutLog("Found project on Db without the folder and erased it! Prod number " & Project.nProdId.ToString("0000"))
                  End If
               End If
            Next
         Else
            For Each Project In DbProjectList
               ' recupero path per verificare esista
               If IsNothing(Project.nProdId) OrElse Project.nProdId = 0 Then Continue For
               Dim sPath As String = Map.refMainWindowVM.MainWindowM.sProdsDir & "\" & Project.nProdId.ToString("0000") & "\" & Project.nProdId.ToString("0000") & ".nge"
               If File.Exists(sPath) Then
                  m_ProjectList.Add(New ProdFileVM(Project))
               Else
                  DbControllers.m_ProdController.DeleteProd(Project.nProdId, True)
                  EgtOutLog("Found project on Db without the folder and erased it! Prod number " & Project.nProdId.ToString("0000"))
               End If
            Next
         End If
      End If
   End Sub

   Public Overrides Sub Delete()
      If IsNothing(SelProject) Then Return
      ' recupero indice per riselezionare
      Dim ProjListIndex As Integer = m_ProjectList.IndexOf(SelProject)
      If m_ProjectType = ProjectType.PROJ Then
         ' verifico se proj selezionato e' il corrente
         If Not IsNothing(Map.refProjManagerVM.CurrProj) AndAlso SelProject.nProjId = Map.refProjManagerVM.CurrProj.nProjId Then
            MessageBox.Show(EgtMsg(61872), EgtMsg(30009), MessageBoxButton.OK, MessageBoxImage.Warning)
            Return
         End If
         ' verifico se proj selezionato ha prod 
         If SelProject.nProdId > 0 Then
            MessageBox.Show(EgtMsg(61873), EgtMsg(30009), MessageBoxButton.OK, MessageBoxImage.Warning)
            Return
         End If
         Map.refProjManagerVM.m_MruFiles.Remove(SelProject.sProjPath)
         Map.refProjManagerVM.NotifyPropertyChanged(NameOf(Map.refProjManagerVM.MruFileNames))
         ' cancello progetto
         ' CheckMe impostata come cancellazione FISICA dal DB...
         DbControllers.m_ProjController.DeleteProj(SelProject.nProjId, False)
         ' cancello cartella del Proj
         Try
            Directory.Delete(SelProject.sProjDirPath, True)
         Catch ex As Exception
            EgtOutLog("Error in deleting directory " & SelProject.sProjDirPath)
         End Try
         ' aggiorno lista progetti
         m_ProjectList.Clear()
         Dim DbProjectList As New List(Of ProjFileM)
         DbProjectList = DbControllers.m_ProjController.GetLastDesc(50, False)
         For Each Project In DbProjectList
            m_ProjectList.Add(New ProjFileVM(Project))
         Next
      ElseIf m_ProjectType = ProjectType.PROD Then
         ' verifico se prod selezionato e' il corrente
         If Not IsNothing(Map.refProdManagerVM.CurrProd) AndAlso SelProject.nProdId = Map.refProdManagerVM.CurrProd.nProdId Then
            MessageBox.Show(EgtMsg(61872), EgtMsg(30009), MessageBoxButton.OK, MessageBoxImage.Warning)
            Return
         End If
         ' verifico se ci sono grezzi mandati al supervisore
         If DbControllers.m_ProdController.IsAnyInSupervisor(SelProject.nProdId) Then
            MessageBox.Show(EgtMsg(61874), EgtMsg(30009), MessageBoxButton.OK, MessageBoxImage.Warning)
            Return
         End If
         Map.refProdManagerVM.m_MruFiles.Remove(SelProject.sProdPath)
         Map.refProdManagerVM.NotifyPropertyChanged(NameOf(Map.refProdManagerVM.MruFileNames))
         ' cancello progetto
         DbControllers.m_ProdController.DeleteProd(SelProject.nProdId, True)
         ' riporto prod in proj
         Dim nCurrCtx As Integer = EgtGetCurrentContext()
         Dim nTempCtx As Integer = EgtInitContext()
         If nTempCtx <> 0 Then
            ' inizializzo gestore lavorazioni
            EgtInitMachMgr(Map.refMainWindowVM.MainWindowM.sMachinesRoot, Map.refMainWindowVM.MainWindowM.sToolMakersDir)
            ' apro, ripulisco e salvo il progetto in tutti i proj correlati
            Dim ProdFile As ProdFileVM = DirectCast(SelProject, ProdFileVM)
            For Each nProjId In ProdFile.nProjIdList
               EgtOpenFile(SelProject.sProdPath)
               ' cancello tutti i gruppi di lavorazione
               Dim nMachGroupId As Integer = EgtGetFirstMachGroup()
               While nMachGroupId <> GDB_ID.NULL
                  EgtSetCurrMachGroup(nMachGroupId)
                  Dim nRawPartId As Integer = EgtGetFirstRawPart()
                  While nRawPartId <> GDB_ID.NULL
                     Dim nPartId As Integer = EgtGetFirstPartInRawPart(nRawPartId)
                     While nPartId <> GDB_ID.NULL
                        EgtRemovePartFromRawPart(nPartId)
                        ' elimino pezzo copia
                        EgtErase(nPartId)
                        nPartId = EgtGetFirstPartInRawPart(nRawPartId)
                     End While
                     nRawPartId = EgtGetNextRawPart(nRawPartId)
                  End While
                  EgtRemoveMachGroup(nMachGroupId)
                  nMachGroupId = EgtGetFirstMachGroup()
               End While
               ' cancello tutti i gruppi che sono di un progetto diverso da questo
               Dim nGroupId As Integer = EgtGetFirstInGroup(GDB_ID.ROOT)
               While nGroupId <> GDB_ID.NULL
                  Dim nGroupProjId As Integer = GDB_ID.NULL
                  Dim nNextGroupId As Integer = EgtGetNext(nGroupId)
                  If EgtGetInfo(nGroupId, BTL_PRT_PROJ, nGroupProjId) Then
                     If nGroupProjId <> nProjId Then
                        EgtErase(nGroupId)
                     End If
                  End If
                  nGroupId = nNextGroupId
               End While
               EgtSaveFile(ProdFile.GetProjPath(nProjId), NGE.CMPTEXT)
            Next
            ' torno sul contesto corrente
            EgtSetCurrentContext(nCurrCtx)
            EgtDeleteContext(nTempCtx)
         End If
         ' se proj corrente era il prod cancellato, aggiorno proj corrente
         If Not IsNothing(Map.refProjManagerVM.CurrProj) AndAlso Map.refProjManagerVM.CurrProj.nProdId = SelProject.nProdId Then
            Map.refProjManagerVM.UpdateCurrProj()
         End If
         ' cancello cartella del Prod
         Try
            Directory.Delete(SelProject.sProdDirPath, True)
         Catch ex As Exception
            EgtOutLog("Error in deleting directory " & SelProject.sProdDirPath)
         End Try
         ' aggiorno lista progetti
         m_ProjectList.Clear()
         Dim DbProjectList As New List(Of ProdFileM)
         DbProjectList = DbControllers.m_ProdController.GetLastDesc(50, False)
         For Each Project In DbProjectList
            m_ProjectList.Add(New ProdFileVM(Project))
         Next
      End If
      ' ripristino selezionato
      If ProjListIndex >= 0 AndAlso ProjListIndex <= m_ProjectList.Count - 1 Then
         SelProject = m_ProjectList(ProjListIndex)
         NotifyPropertyChanged(NameOf(SelProject))
      End If
      ' reset dei controller per tornare in sync
      DbControllers.m_ProjController.ResetController()
      DbControllers.m_ProdController.ResetController()
   End Sub

#End Region    ' METHODS

End Class
