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

Public Class NewOpenProjectFileDialogVM
   Inherits Core.NewOpenProjectFileDialogVM

   Public Overrides ReadOnly Property DayTypeList As List(Of String)
      Get
         Dim CurrDayTypeList As New List(Of String)({EgtMsg(62532), EgtMsg(62533), EgtMsg(62534), EgtMsg(62531)})
         If Map.refMainWindowVM.MainWindowM.nUserLevel > 5 Then
            CurrDayTypeList.Add("Always")
         End If
         Return CurrDayTypeList
      End Get
   End Property

#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

      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)
         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
         Case DayTypes.ALWAYS
            dtEnd = DateTime.Today + TimeSpan.FromDays(1)
            dtStart = New DateTime(2020, 1, 1)
      End Select
      ' leggo da db
      If m_ProjectType = ProjectType.PROJ Then
         Dim DbProjList As New List(Of ProjFileM)
         If m_SelBTLDateType = BTLDateTypes.CREATEDATE Then
            DbProjList = DbControllers.m_ProjController.GetLastDesc(dtStart, dtEnd, nRowQuantity * 3, True, bViewArchived)
         Else
            DbProjList = DbControllers.m_ProjController.GetLastByExpDesc(dtStart, dtEnd, nRowQuantity * 3, True, bViewArchived)
         End If
         For Each Project In DbProjList
            If IsNothing(Project.nProjId) OrElse Project.nProjId = 0 Then Continue For
            ' verifico se ha prod
            If Not IsNothing(Project.nProdId) And Project.nProdId > 0 Then
               ' verifico se prod e' gia' stato creato
               Dim SameProdItem As ProdItem = m_ProjectList.FirstOrDefault(Function(x) Not IsNothing(x.ProdFileVM) AndAlso Not IsNothing(x.ProdFileVM.nProdId) AndAlso x.ProdFileVM.nProdId = Project.nProdId)
               If Not IsNothing(SameProdItem) Then
                  SameProdItem.ProjFileList.Add(New ProjFileVM(Project))
               Else
                  ' recupero Prod
                  Dim NewDbProd As ProdFileM = DbControllers.m_ProdController.FindCoreByProdId(Project.nProdId)
                  If Not IsNothing(NewDbProd) Then
                     m_ProjectList.Add(New ProdItem(New ProdFileVM(NewDbProd), New ProjFileVM(Project)))
                  End If
               End If
            Else
               m_ProjectList.Add(New ProdItem(New ProjFileVM(Project)))
            End If
         Next
      ElseIf m_ProjectType = ProjectType.PROD Then
         Dim DbProdList As New List(Of ProdFileM)
         DbProdList = DbControllers.m_ProdController.GetLastDesc(dtStart, dtEnd, nRowQuantity, True, bViewArchived)
         If GoToProd Then
            For Each Project In DbProdList
               ' 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 ProdItem(New ProdFileVM(Project)))
                     'Else
                     '   DbControllers.m_ProdController.DeleteProd(Project.nProdId)
                     '   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 DbProdList
               ' 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
                  ' recupero i proj
                  Dim ProjList As New List(Of ProjectFileVM)
                  For Each ProjFileId In Project.nProjIdList
                     Dim ProjFileM As ProjectFileM = DbControllers.m_ProjController.FindByProjIdConv(ProjFileId)
                     ProjList.Add(New ProjFileVM(ProjFileM))
                  Next
                  m_ProjectList.Add(New ProdItem(New ProdFileVM(Project), ProjList))
                  'Else
                  '   DbControllers.m_ProdController.DeleteProd(Project.nProdId)
                  '   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 Archive()
      If IsNothing(SelProject) Then Return
      If Not IsNothing(SelProject.ProdFileVM) Then
         ' archivio il progetto
         DbControllers.m_ProdController.UpdateArchived(SelProject.ProdFileVM.nProdId, Not SelProject.bIsArchived)
         NotifyPropertyChanged(NameOf(Archive_Msg))
      End If
      ' aggiorno lista progetti
      RefreshProjectList()
   End Sub

   Public Overrides Sub Delete()
      If IsNothing(SelProject) Then Return
      ' recupero indice per riselezionare
      Dim ProjListIndex As Integer = m_ProjectList.IndexOf(SelProject)
      ' verifico se proj selezionato e' il corrente
      If Not IsNothing(Map.refProjManagerVM.CurrProj) AndAlso SelProject.ProjFileList.Any(Function(x) x.nProjId = Map.refProjManagerVM.CurrProj.nProjId) Then
         If m_ProjectType = ProjectType.PROJ AndAlso MessageBox.Show(EgtMsg(61872), EgtMsg(30009), MessageBoxButton.OKCancel, MessageBoxImage.Warning) = MessageBoxResult.Cancel Then
            Return
         Else
            m_ChangeOpenedProjectOnCancel = True
         End If
      End If
      ' verifico se prod selezionato e' il corrente
      If Not IsNothing(Map.refProdManagerVM.CurrProd) AndAlso SelProject.ProdFileVM.nProdId = Map.refProdManagerVM.CurrProd.nProdId Then
         If m_ProjectType = ProjectType.PROD AndAlso MessageBox.Show(EgtMsg(61872), EgtMsg(30009), MessageBoxButton.OKCancel, MessageBoxImage.Warning) = MessageBoxResult.Cancel Then
            Return
         Else
            m_ChangeOpenedProjectOnCancel = True
         End If
      End If
      ' rimuovo da lista ultimi progetti aperti
      For Each Project In SelProject.ProjFileList
         Map.refProjManagerVM.m_MruFiles.Remove(Project.sProjPath)
      Next
      Map.refProjManagerVM.NotifyPropertyChanged(NameOf(Map.refProjManagerVM.MruFileNames))
      If Not IsNothing(SelProject.ProdFileVM) Then
         Map.refProdManagerVM.m_MruFiles.Remove(SelProject.ProdFileVM.sProdPath)
         Map.refProdManagerVM.NotifyPropertyChanged(NameOf(Map.refProdManagerVM.MruFileNames))
      End If
      ' cancello progetto
      If Not IsNothing(SelProject.ProdFileVM) Then
         DbControllers.m_ProdController.DeleteProd(SelProject.ProdFileVM.nProdId, True)
         '' cancello cartella del Prod
         'Try
         '   Directory.Delete(SelProject.ProdFileVM.sProdDirPath, True)
         'Catch ex As Exception
         '   EgtOutLog("Error in deleting directory " & SelProject.ProdFileVM.sProdDirPath)
         'End Try
      End If
      For Each Project In SelProject.ProjFileList
         DbControllers.m_ProjController.DeleteProj(Project.nProjId, True)
         '' cancello cartella del Proj
         'Try
         '   Directory.Delete(Project.sProjDirPath, True)
         'Catch ex As Exception
         '   EgtOutLog("Error in deleting directory " & Project.sProjDirPath)
         'End Try
      Next
      ' aggiorno lista progetti
      RefreshProjectList()
      ' 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

   Public Overrides Sub Cancel()
      If m_ChangeOpenedProjectOnCancel Then
         Dim bOpened As Boolean = False
         If m_ProjectType = ProjectType.PROJ Then
            For Each ProjectName In Map.refProjManagerVM.m_MruFiles.FileNames
               If Not String.IsNullOrWhiteSpace(ProjectName) Then
                  Dim sProjId As String = Path.GetFileNameWithoutExtension(ProjectName)
                  If Not String.IsNullOrWhiteSpace(sProjId) Then
                     Dim nProjId As Integer = 0
                     Integer.TryParse(sProjId, nProjId)
                     Dim PjFileM = DbControllers.m_ProjController.FindByProjIdConv(nProjId)
                     Dim PjFileVM = New ProjFileVM(PjFileM)
                     Map.refProjManagerVM.OpenProject(PjFileVM)
                     bOpened = True
                     Exit For
                  End If
               End If
            Next
            If Not bOpened Then
               Map.refProjManagerVM.OpenProject(m_ProjectList(0).ProjFileList(0))
            End If
         ElseIf m_ProjectType = ProjectType.PROD Then
            For Each ProjectName In Map.refProdManagerVM.m_MruFiles.FileNames
               If Not String.IsNullOrWhiteSpace(ProjectName) Then
                  Dim sProdId As String = Path.GetFileNameWithoutExtension(ProjectName)
                  If Not String.IsNullOrWhiteSpace(sProdId) Then
                     Dim nProdId As Integer = 0
                     Integer.TryParse(sProdId, nProdId)
                     Dim PjFileM = DbControllers.m_ProdController.FindCoreByProdId(nProdId)
                     Dim PjFileVM = New ProdFileVM(PjFileM)
                     Map.refProdManagerVM.OpenProject(PjFileVM)
                     bOpened = True
                     Exit For
                  End If
               End If
            Next
         End If
      End If
      CloseWindow(False)
   End Sub

#End Region    ' METHODS

End Class

Public Class ProdItem
   Inherits Core.ProdItem

   Public Overrides Property sName As String
      Get
         Return If(Not IsNothing(m_ProdFileVM), m_ProdFileVM.sName, "")
      End Get
      Set(value As String)
         If Not IsNothing(m_ProdFileVM) Then
            DbControllers.m_ProdController.UpdateDescription(m_ProdFileVM.nProdId, value)
            m_ProdFileVM.sName = value
            m_delIsModifiedSetUp(False)
         End If
      End Set
   End Property

   Sub New(ProdFileVM As ProdFileVM, ProjFileVM As ProjFileVM)
      MyBase.New(ProdFileVM, ProjFileVM)
   End Sub

   Sub New(ProjFileVM As ProjFileVM)
      MyBase.New(ProjFileVM)
   End Sub

   Sub New(ProdFileVM As ProjectFileVM, ProjFileVMList As List(Of ProjectFileVM))
      MyBase.New(ProdFileVM, ProjFileVMList)
   End Sub

End Class