Imports EgtBEAMWALL.Core
Imports EgtBEAMWALL.DataLayer.DatabaseModels

Public Class SupervisorComm

   Private m_BlockedWnd As BlockedWndV
   Private m_bTickInExecution As Boolean = False

   Private m_CurrSession_ProdId As Integer = 0
   Private m_CurrSession_Index As Integer = 0

   Sub New()
      ' imposto in Map
      'Map.SetRefMachManaging(Me)
   End Sub

   Friend Sub Timer_Tick()
      If m_bTickInExecution Then
         EgtUILib.EgtOutLog("Tick gia' in esecuzione!!")
         Return
      End If
      m_bTickInExecution = True
      ' se arriva info di cambio progetto
      Dim ActiveSessionList As List(Of StatusMapModel) = DbControllers.m_StatusMapController.GetProd(m_SupervisorId)
      Dim MySession As StatusMapModel = ActiveSessionList.FirstOrDefault(Function(x) x.Session = DbControllers.m_SupervisorId)
      If Not IsNothing(MySession) Then
         If m_CurrSession_ProdId <> MySession.ItemId OrElse MySession.Index < m_CurrSession_Index Then
            m_CurrSession_ProdId = MySession.ItemId
            m_CurrSession_Index = MySession.Index
         End If
         If MySession.Index > m_CurrSession_Index Then
            ' recupero elementi modificati
            Dim MessagesList As List(Of StatusMapModel) = DbControllers.m_StatusMapController.GetFrom(m_SupervisorId, m_CurrSession_Index + 1)
            For Each Message In MessagesList
               Select Case Message.ItemType
                  Case StatusMapItemType.Comm
                     Select Case Message.Operation
                        Case StatusMapOpType.ChangeProdInProdRequest
                           Map.refProdManagerVM.OpenProjectFromSupervisor(Message.ItemId)
                        Case StatusMapOpType.OpenPageInViewOptimRequest
                           Map.refMainMenuVM.OpenPageFromSupervisor(Math.Abs(Message.ItemId))
                     End Select
               End Select
            Next
            m_CurrSession_Index = MySession.Index
         End If
      End If
      ' se sono in pagina vista
      If Map.refMainMenuVM.SelPage = Pages.VIEW Then
         ' se non c'e' un progetto attivo, esco
         If IsNothing(Map.refProjManagerVM.CurrProj) Then
            m_bTickInExecution = False
            Return
         End If
         ' verifico se c'e' un progetto aperto o in caricamento
         'If IsNothing(Map.refProjManagerVM.CurrProj) OrElse Map.refProjManagerVM.bLoadingProj Then Return
         ' verifico se c'e' una sessione aperta sul progetto corrente
         Dim nModificationIndex As Integer = -1
         ActiveSessionList = DbControllers.m_StatusMapController.GetProd(m_SupervisorId)
         For Each ActiveSession In ActiveSessionList
            If ActiveSession.ItemId = Map.refProjManagerVM.CurrProj.nProdId Then
               nModificationIndex = ActiveSession.Index
            End If
         Next
         If nModificationIndex = -1 Then
            m_bTickInExecution = False
            Return
         End If
         ' verifico se ci sono modifiche
         If nModificationIndex <> Map.refProjManagerVM.CurrProj.nModificationIndex Then
            ' recupero elementi modificati
            Dim MachGroupList As List(Of StatusMapModel) = DbControllers.m_StatusMapController.GetFrom(m_SupervisorId, Map.refProjManagerVM.CurrProj.nModificationIndex + 1)
            Dim bReloadFile As Boolean = False
            If Not IsNothing(MachGroupList) Then
               For Each MachGroupModification In MachGroupList
                  If MachGroupModification.ItemType = StatusMapItemType.Part Then
                     Dim BTLPart As BTLPartVM = CALCPanelVM.GetBTLPartVMFromPartId(MachGroupModification.ItemId)
                     If Not IsNothing(BTLPart) Then
                        Select Case MachGroupModification.Operation
                           Case Core.StatusMapOpType.PartStart
                        ' non faccio nulla
                           Case Core.StatusMapOpType.PartEnd, StatusMapOpType.ResetPartStart, StatusMapOpType.ResetPartEnd
                              BTLPart.NotifyPropertyChanged(NameOf(BTLPart.nDONE))
                              BTLPart.NotifyPropertyChanged(NameOf(BTLPart.Background))
                        End Select
                     End If
                  ElseIf MachGroupModification.ItemType = StatusMapItemType.Comm Then
                     ' se arriva richiesta da supervisore di blocco e salvataggio
                     Select Case MachGroupModification.Operation
                        Case StatusMapOpType.SupervisorStopRequest
                           ' blocco interfaccia fino a notifica di sblocco
                           SupervisorCommThread.SetViewerOptimizerBlocked(True)
                        '' chiedo se salvare
                        Case StatusMapOpType.SupervisorReleaseStop
                           SupervisorCommThread.SetViewerOptimizerBlocked(False)
                     End Select
                  End If
               Next
            End If
            ' aggiorno indice del proj
            Map.refProjManagerVM.CurrProj.SetModificationIndex(nModificationIndex)
         End If
         ' se sono in pagina ottimizzatore
      ElseIf Map.refMainMenuVM.SelPage = Pages.MACHINING Then
         ' se non c'e' un progetto attivo, esco
         If IsNothing(Map.refProdManagerVM.CurrProd) Then
            m_bTickInExecution = False
            Return
         End If
         ' verifico se c'e' un progetto aperto o in caricamento
         'If IsNothing(Map.refProdManagerVM.CurrProd) OrElse Map.refProdManagerVM.bLoadingProd Then Return
         ' verifico se c'e' una sessione aperta sul progetto corrente
         Dim nModificationIndex As Integer = -1
         ActiveSessionList = DbControllers.m_StatusMapController.GetProd(m_SupervisorId)
         For Each ActiveSession In ActiveSessionList
            If Not IsNothing(Map.refProdManagerVM.CurrProd) AndAlso ActiveSession.ItemId = Map.refProdManagerVM.CurrProd.nProdId Then
               nModificationIndex = ActiveSession.Index
            End If
         Next
         If nModificationIndex = -1 Then
            m_bTickInExecution = False
            Return
         End If
         ' verifico se ci sono modifiche
         If nModificationIndex <> Map.refProdManagerVM.CurrProd.nModificationIndex Then
            ' recupero elementi modificati
            Dim MachGroupList As List(Of StatusMapModel) = DbControllers.m_StatusMapController.GetFrom(m_SupervisorId, Map.refProdManagerVM.CurrProd.nModificationIndex + 1)
            If Not IsNothing(MachGroupList) Then
               Dim bReloadFile As Boolean = False
               For Each MachGroupModification In MachGroupList
                  If MachGroupModification.ItemType = StatusMapItemType.MachGroup Then
                     Dim MachGroup As MyMachGroupVM = Map.refProjectVM.MachGroupPanelVM.MachGroupVMList.FirstOrDefault(Function(x) x.Id = MachGroupModification.ItemId)
                     If Not IsNothing(MachGroup) Then
                        Select Case MachGroupModification.Operation
                           Case Core.StatusMapOpType.PartStart
                              MachGroup.dtStartTime = MachGroupModification.DtEvent
                              MachGroup.nProduction_State = ItemState.WIP
                              MachGroup.NotifyPropertyChanged(NameOf(MachGroup.nProduction_State))
                              MachGroup.NotifyPropertyChanged(NameOf(MachGroup.Background))
                           Case Core.StatusMapOpType.PartEnd
                              MachGroup.dtEndTime = MachGroupModification.DtEvent
                              MachGroup.nProduction_State = ItemState.Produced
                              MachGroup.NotifyPropertyChanged(NameOf(MachGroup.Background))
                           Case Core.StatusMapOpType.ResetPartStart
                              MachGroup.dtStartTime = DateTime.MinValue
                              MachGroup.nProduction_State = ItemState.Assigned
                              MachGroup.NotifyPropertyChanged(NameOf(MachGroup.nProduction_State))
                              MachGroup.NotifyPropertyChanged(NameOf(MachGroup.Background))
                           Case Core.StatusMapOpType.ResetPartEnd
                              MachGroup.dtEndTime = DateTime.MinValue
                              MachGroup.nProduction_State = ItemState.WIP
                              MachGroup.NotifyPropertyChanged(NameOf(MachGroup.nProduction_State))
                              MachGroup.NotifyPropertyChanged(NameOf(MachGroup.Background))
                           Case Core.StatusMapOpType.MachGroupRemovedFromSupervisor
                              MachGroup.ResetSupervisorId()
                           Case Core.StatusMapOpType.MachGroupValidationUpdate
                              CALCPanelVM.ProcessResults(MachGroup)
                        End Select
                     End If
                  ElseIf MachGroupModification.ItemType = StatusMapItemType.Part Then
                     Dim BTLPart As BTLPartVM = CALCPanelVM.GetBTLPartVMFromPartId(MachGroupModification.ItemId)
                     Dim Part As PartVM = CALCPanelVM.GetPartVMFromPartId(MachGroupModification.ItemId)
                     Select Case MachGroupModification.Operation
                        Case Core.StatusMapOpType.PartStart
                           If Not IsNothing(Part) Then
                              Part.dtStartTime = MachGroupModification.DtEvent
                              Part.nProduction_State = ItemState.WIP
                              Part.NotifyPropertyChanged(NameOf(Part.Background))
                           End If
                        Case Core.StatusMapOpType.PartEnd
                           If Not IsNothing(Part) Then
                              Part.dtEndTime = MachGroupModification.DtEvent
                              Part.nProduction_State = ItemState.Produced
                              Part.NotifyPropertyChanged(NameOf(Part.Background))
                           End If
                           If Not IsNothing(BTLPart) Then
                              BTLPart.NotifyPropertyChanged(NameOf(BTLPart.nDONE))
                              BTLPart.NotifyPropertyChanged(NameOf(BTLPart.Background))
                           End If
                        Case Core.StatusMapOpType.ResetPartStart
                           If Not IsNothing(Part) Then
                              Part.dtStartTime = DateTime.MinValue
                              Part.nProduction_State = ItemState.Assigned
                              Part.NotifyPropertyChanged(NameOf(Part.Background))
                           End If
                        Case Core.StatusMapOpType.ResetPartEnd
                           If Not IsNothing(Part) Then
                              Part.dtEndTime = DateTime.MinValue
                              Part.nProduction_State = ItemState.WIP
                              Part.NotifyPropertyChanged(NameOf(Part.Background))
                           End If
                           If Not IsNothing(BTLPart) Then
                              BTLPart.NotifyPropertyChanged(NameOf(BTLPart.nDONE))
                              BTLPart.NotifyPropertyChanged(NameOf(BTLPart.Background))
                           End If
                        Case Core.StatusMapOpType.SetPartScrapped
                           If Not IsNothing(Part) Then
                              Part.nProduction_State = ItemState.Scrapped
                              Part.NotifyPropertyChanged(NameOf(Part.Background))
                           End If
                     End Select
                  ElseIf MachGroupModification.ItemType = StatusMapItemType.Comm Then
                     ' se arriva richiesta da supervisore di blocco e salvataggio
                     Select Case MachGroupModification.Operation
                        Case StatusMapOpType.SupervisorStopRequest
                           ' blocco interfaccia fino a notifica di sblocco
                           SupervisorCommThread.SetViewerOptimizerBlocked(True)
                        '' chiedo se salvare
                        'Map.refMainWindowVM.m_SupervisorStop = True
                        Case StatusMapOpType.SupervisorReleaseStop
                           Dim MachGroupId As Integer = -1
                           If Not String.IsNullOrWhiteSpace(MachGroupModification.Val) Then Integer.TryParse(MachGroupModification.Val, MachGroupId)
                           If IsNothing(MachGroupId) Then MachGroupId = -1
                           SupervisorCommThread.SetViewerOptimizerBlocked(False, MachGroupId)
                           'Map.refMainWindowVM.m_SupervisorStop = False
                     End Select
                  End If
               Next
            End If
            ' aggiorno indice del prod
            Map.refProdManagerVM.CurrProd.SetModificationIndex(nModificationIndex)
         End If
      End If
      ' se c'e' un progetto aperto o in caricamento
      'If IsNothing(Map.refProdManagerVM.CurrProd) OrElse Map.refProdManagerVM.bLoadingProd Then Return
      '' recupero indice modifica del prod
      'Dim nModificationIndex As Integer = 0
      'Dim ActiveSessionList As List(Of StatusMapModel) = DbControllers.m_StatusMapController.GetProd()
      'For Each ActiveSession In ActiveSessionList
      '   If ActiveSession.ItemId = Map.refSupervisorManagerVM.CurrProd.nProdId Then
      '      nModificationIndex = ActiveSession.Index
      '   End If
      'Next
      '' se indice letto diverso da indice gia' presente
      'If nModificationIndex <> Map.refSupervisorManagerVM.CurrProd.nModificationIndex Then
      '   ' recupero elementi modificati
      '   Dim MachGroupList As List(Of StatusMapModel) = DbControllers.m_StatusMapController.GetFrom(Map.refSupervisorManagerVM.CurrProd.nModificationIndex + 1)
      '   Dim bReloadFile As Boolean = False
      '   For Each MachGroupModification In MachGroupList
      '      Select Case MachGroupModification.Operation
      '         Case Core.StatusMapOpType.MachGroupAdd
      '            Map.refProjectVM.SupervisorMachGroupPanelVM.MachGroupFullList.Add(MachGroupModification.ItemId, {MachGroupModification.Index, MachGroupModification.Index})
      '         Case Core.StatusMapOpType.MachGroupMod
      '            Map.refProjectVM.SupervisorMachGroupPanelVM.MachGroupFullList(MachGroupModification.ItemId)(0) = MachGroupModification.Index
      '         Case Core.StatusMapOpType.MachGroupRem
      '            Map.refProjectVM.SupervisorMachGroupPanelVM.MachGroupFullList.Remove(MachGroupModification.ItemId)
      '         Case Core.StatusMapOpType.MachGroupAssignedToSupervisor
      '            Dim MachgroupIndexes As Integer() = Map.refProjectVM.SupervisorMachGroupPanelVM.MachGroupFullList(MachGroupModification.ItemId)
      '            ' se indice di aggiornamento file diverso da indice ultima modifica
      '            If MachgroupIndexes(0) <> MachgroupIndexes(1) Then
      '               ' devo ricaricare il file
      '               bReloadFile = True
      '               ' ricarico il progetto
      '               Map.refProjectVM.SupervisorMachGroupPanelVM.ReloadProjectFile()
      '            End If
      '            ' lo aggiungo alla lista di MachGroup
      '            Map.refProjectVM.SupervisorMachGroupPanelVM.AddMachGroupToSupervisor(Map.refProjectVM.ProdMachGroupPanelVM.MachGroupVMList.FirstOrDefault(Function(x) x.Id = MachGroupModification.ItemId))
      '      End Select
      '   Next
      '   ' se devo ricaricare il file
      '   If bReloadFile Then
      '      ' aggiorno indici in dictionary
      '      For Each MachGroupModification In Map.refProjectVM.SupervisorMachGroupPanelVM.MachGroupFullList.Where(Function(x) x.Value(0) <> x.Value(1))
      '         MachGroupModification.Value(1) = MachGroupModification.Value(0)
      '      Next

      '      ' ricarico il progetto
      '      'Map.refProjectVM.SupervisorMachGroupPanelVM.ReloadProjectFile()
      '   End If

      '   ' aggiorno indice del prod
      '   Map.refSupervisorManagerVM.CurrProd.SetModificationIndex(nModificationIndex)
      'End If

      '' verifico se e' aperto in qualche ottimizzatore
      ''DbControllers.m_ProdController.
      ''Map.refSupervisorManagerVM.CurrProd.bIsLocked
      '' verifico se la mappa messaggi ha indice maggiore del mio

      '' ricarico il progetto

      '' aggiorno eventuali nuovi machgroup

      '' se devo ripartire a meta' di una barra

      '' mando messaggio di blocco dell'ottimizzatore

      m_bTickInExecution = False
   End Sub

End Class