Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.IO
Imports System.Windows.Threading
Imports EgtBEAMWALL.Core
Imports EgtBEAMWALL.DataLayer.DatabaseModels
Imports EgtUILib
Imports EgtWPFLib5

Public Class SupervisorMachGroupPanelVM
   Inherits MyMachGroupPanelVM

#Region "FIELDS & PROPERTIES"

   Private m_ReloadProj_Timer As New DispatcherTimer
   Private m_bReloadProj As Boolean = False
   Private m_bReloadingProj As Boolean = False
   Public ReadOnly Property bReloadingProj As Boolean
      Get
         Return m_bReloadingProj
      End Get
   End Property

   Private m_MachGroupVMList_View As ListCollectionView = Nothing
   Public ReadOnly Property MachGroupVMList_View As ListCollectionView
      Get
         Return m_MachGroupVMList_View
      End Get
   End Property

   ' lock per aggiunta elemento a lista MachGroup
   Private m_Lock_AddMachGroup As New Object

   ' Dictionari delle modifiche sui machgroup
   ' key => LastModificationIndex, LastFileLoadIndex
   Private m_MachGroupFullList As New Dictionary(Of Integer, Integer())
   Public Property MachGroupFullList As Dictionary(Of Integer, Integer())
      Get
         Return m_MachGroupFullList
      End Get
      Set(value As Dictionary(Of Integer, Integer()))
         m_MachGroupFullList = value
      End Set
   End Property

#End Region    ' FIELDS & PROPERTIES

#Region "CONSTRUCTOR"
   Private m_MachGroupVMListComparer As MyComparer
   Friend ReadOnly Property MachGroupVMListComparer As MyComparer
      Get
         Return m_MachGroupVMListComparer
      End Get
   End Property

   Friend Sub SetMachGroupVMListView()
      m_MachGroupVMList_View = CollectionViewSource.GetDefaultView(m_MachGroupVMList)
      m_MachGroupVMListComparer = New MyComparer
      m_MachGroupVMList_View.CustomSort = m_MachGroupVMListComparer
      NotifyPropertyChanged(NameOf(MachGroupVMList_View))
   End Sub

   Friend Sub RefreshMachGroupVMSort()
      m_MachGroupVMList_View.CustomSort = m_MachGroupVMListComparer
   End Sub

   Sub New(MachGroupPanelM As MachGroupPanelM)
      MyBase.New(MachGroupPanelM)
      ' riferimento su map
      Map.SetRefSupervisorMachGroupPanelVM(Me)
      BindingOperations.EnableCollectionSynchronization(m_MachGroupVMList, m_Lock_AddMachGroup)
      m_ReloadProj_Timer.Interval = TimeSpan.FromMilliseconds(500)
      AddHandler m_ReloadProj_Timer.Tick, AddressOf ReloadProject_Tick
      m_ReloadProj_Timer.Start()
   End Sub

#End Region    ' CONSTRUCTOR

#Region "METHODS"

   Public Sub AddMachGroupToSupervisor(MachGroup As MyMachGroupVM)
      If MachGroupVMList.Count = 0 Then
         ManageBTLParts.ShowAll()
      End If
      If Not MachGroupVMList.Contains(MachGroup) Then
         SyncLock (m_Lock_AddMachGroup)
            MachGroupVMList.Add(MachGroup)
         End SyncLock
      End If
      ' notifico stato
      MachGroup.NotifyPropertyChanged(NameOf(MachGroup.Produce_IsEnabled))
   End Sub

   Public Sub ReloadProjectFile()
      m_bReloadProj = True
   End Sub

   Public Sub ReloadProject_Tick()
      If Not m_bReloadProj Then Return
      m_bReloadingProj = True
      m_bReloadProj = False
      Map.refSceneHostVM.MainController.ResetModified()
      Map.refSceneHostVM.MainController.OpenProject(Map.refSupervisorManagerVM.CurrProd.sProdPath, False)
      RefreshSupervisorMachGroups(Map.refMachinePanelVM.MachineList.ToList())
      m_bReloadingProj = False
   End Sub

#End Region    ' CONSTRUCTOR

#Region "METHODS"

   Public Shared Sub RefreshSupervisorMachGroups(MachineList As List(Of Machine))
      ' Carico tutti i gruppi di lavorazione aggiunti al progetto
      Dim nId = EgtGetFirstMachGroup()
      While nId <> GDB_ID.NULL
         '  se gia' presente, vado al prossimo
         If Map.refProjectVM.ProdMachGroupPanelVM.MachGroupVMList.Any(Function(x) x.Id = nId) Then
            nId = EgtGetNextMachGroup(nId)
            Continue While
         End If
         ' altrimenti lo carico
         EgtSetCurrMachGroup(nId)
         Dim sName As String = String.Empty
         Dim sMachine As String = String.Empty
         EgtGetMachGroupName(nId, sName)
         EgtGetMachGroupMachineName(nId, sMachine)
         ' cerco la macchina tra quelle presenti
         Dim UsedMachine As MyMachine = Nothing
         Dim bOk As Boolean = Machine.SearchMachine(sMachine, MachineList, UsedMachine)
         If Not bOk OrElse UsedMachine.nType = MachineType.NULL Then
            EgtOutLog("Machine incompatible with beam & wall machining!!")
         Else
            Map.refProjectVM.ProdMachGroupPanelVM.m_MyMachGroupPanelM.AddMachGroup(MyMachGroupM.CreateMyMachGroup(UsedMachine.nType, nId, sName, sMachine))
         End If
         nId = EgtGetNextMachGroup(nId)
      End While
      EgtResetCurrMachGroup()
      ' carico solo elementi passati al supervisore
      Dim TempList As List(Of MachGroupModel) = DbControllers.m_MachGroupController.GetByProdSupervisor(Map.refSupervisorManagerVM.CurrProd.nProdId, m_SupervisorId)
      For Each DBMachGroup In TempList
         If Map.refProjectVM.SupervisorMachGroupPanelVM.MachGroupVMList.Any(Function(x) x.Id = DBMachGroup.MachGroupId) Then Continue For
         Dim MachGroup As MyMachGroupVM = Map.refProjectVM.ProdMachGroupPanelVM.MachGroupVMList.FirstOrDefault(Function(x) x.Id = DBMachGroup.MachGroupId)
         ' leggo dati da Db
         MachGroup.dtStartTime = DBMachGroup.DtStart
         MachGroup.dtEndTime = DBMachGroup.DtEnd
         MachGroup.MyMachGroupM.SetProductionState(DBMachGroup.State)
         MachGroup.SetProductionIndex(DBMachGroup.ProdIndex)
         For Each Part In MachGroup.PartVMList
            Dim DBPart As PartModel = DbControllers.m_PartController.FindByPartId(Map.refSupervisorManagerVM.CurrProd.nProdId, Part.nPartId)
            Part.dtStartTime = DBPart.DtStart
            Part.dtEndTime = DBPart.DtEnd
            Part.nProduction_State = DBPart.State
         Next
         Map.refProjectVM.SupervisorMachGroupPanelVM.AddMachGroupToSupervisor(MachGroup)
      Next




      '' Carico i gruppi di lavorazione nella lista
      'Dim nId = EgtGetFirstMachGroup()
      'While nId <> GDB_ID.NULL
      '   '  se gia' presente, vado al prossimo
      '   If Map.refSupervisorMachGroupPanelVM.MachGroupVMList.Any(Function(x) x.Id = nId) Then
      '      nId = EgtGetNextMachGroup(nId)
      '      Continue While
      '   End If
      '   ' altrimenti lo carico
      '   EgtSetCurrMachGroup(nId)
      '   Dim sName As String = String.Empty
      '   Dim sMachine As String = String.Empty
      '   EgtGetMachGroupName(nId, sName)
      '   EgtGetMachGroupMachineName(nId, sMachine)
      '   ' cerco la macchina tra quelle presenti
      '   Dim UsedMachine As MyMachine = Nothing
      '   Dim bOk As Boolean = Machine.SearchMachine(sMachine, MachineList, UsedMachine)
      '   If Not bOk OrElse UsedMachine.nType = MachineType.NULL Then
      '      EgtOutLog("Machine incompatible with beam & wall machining!!")
      '   ElseIf UsedMachine.nType = MachineType.BEAM Then
      '      Map.refSupervisorMachGroupPanelVM.m_MyMachGroupPanelM.AddMachGroup(BeamMachGroupM.CreateBeamMachGroup(nId, sName, sMachine))
      '   ElseIf UsedMachine.nType = MachineType.WALL Then
      '      Map.refSupervisorMachGroupPanelVM.m_MyMachGroupPanelM.AddMachGroup(WallMachGroupM.CreateWallMachGroup(nId, sName, sMachine))
      '   End If
      '   nId = EgtGetNextMachGroup(nId)
      'End While
      'EgtResetCurrMachGroup()

   End Sub

#End Region    ' METHODS

End Class

'Friend Class MachGroupVMListComparer
'   Implements IComparer

'   Dim m_Direction As ListSortDirection
'   Dim m_Column As EgtDataGridColumn
'   Dim m_ColumnList As List(Of DataGridColumn)
'   Dim m_EgtColumnList As New List(Of EgtDataGridColumn)

'   Sub New()
'      m_Column = column
'      m_ColumnList = ColumnList
'      m_EgtColumnList = EgtColumnList
'      m_Direction = direction


'      Dim column As DataGridColumn = e.Column
'      Dim datagrid As DataGrid = sender
'      Dim comparer As IComparer = Nothing
'      e.Handled = True
'      Dim direction As ListSortDirection = If((column.SortDirection <> ListSortDirection.Ascending), ListSortDirection.Ascending, ListSortDirection.Descending)
'      column.SortDirection = direction
'      Dim m_ColumnList As New List(Of DataGridColumn)
'      Dim m_EgtColumnList As New List(Of EgtDataGridColumn)
'      For Each col In datagrid.Columns
'         If Not IsNothing(col.SortDirection) Then
'            m_ColumnList.Add(col)
'            m_EgtColumnList.Add(Map.refRawPartListVM.RawPartColumns(col.DisplayIndex))
'         End If
'      Next
'      Dim lcv As ListCollectionView = CType(CollectionViewSource.GetDefaultView(datagrid.ItemsSource), ListCollectionView)
'      comparer = New MyComparer(Map.refRawPartListVM.RawPartColumns(column.DisplayIndex), m_ColumnList, m_EgtColumnList, direction)
'      lcv.CustomSort = comparer



'   End Sub

'   Public Function Compare(x As Object, y As Object) As Integer Implements IComparer.Compare
'      Dim First As MyMachGroupVM = DirectCast(x, MyMachGroupVM)
'      Dim Second As MyMachGroupVM = DirectCast(y, MyMachGroupVM)
'      Dim bFirstProduced As Boolean = First.nProduction_State = Core.ItemState.WIP OrElse First.nProduction_State = Core.ItemState.Produced
'      Dim bSecondProduced As Boolean = Second.nProduction_State = Core.ItemState.WIP OrElse Second.nProduction_State = Core.ItemState.Produced
'      Dim nDirection As Integer = If(m_Direction, 1, -1)
'      If bFirstProduced AndAlso bSecondProduced Then
'         If First.nProductionIndex > Second.nProductionIndex Then
'            Return 1
'         ElseIf First.nProductionIndex < Second.nProductionIndex Then
'            Return -1
'         Else
'            Return 0
'         End If
'      ElseIf bFirstProduced Then
'         Return -1
'      ElseIf bSecondProduced Then
'         Return 1
'      Else
'         Dim ColumnIndex = 0
'         While ColumnIndex <= m_EgtColumnList.Count - 1
'            Dim nDir As ListSortDirection = If(m_ColumnList(ColumnIndex).SortDirection, 1, -1)
'            Dim nCheck As Integer = Check(First, Second, nDir, m_EgtColumnList(ColumnIndex))
'            If nCheck <> 0 Then
'               Return nCheck
'            End If
'            ColumnIndex += 1
'         End While
'         Return 0
'      End If
'   End Function

'   Private Function Check(First As MyMachGroupVM, Second As MyMachGroupVM, nDirection As Integer, Column As EgtDataGridColumn) As Integer
'      Select Case Column.Name
'         Case COL_NAME
'            If First.nName > Second.nName Then
'               Return 1 * nDirection
'            ElseIf First.nName < Second.nName Then
'               Return -1 * nDirection
'            Else
'               Return 0
'            End If
'         Case COL_STARTCUT
'            If First.Id > Second.Id Then
'               Return 1 * nDirection
'            ElseIf First.Id < Second.Id Then
'               Return -1 * nDirection
'            Else
'               Return 0
'            End If
'         Case COL_W
'            If First.dW > Second.dW Then
'               Return 1 * nDirection
'            ElseIf First.dW < Second.dW Then
'               Return -1 * nDirection
'            Else
'               Return 0
'            End If
'         Case COL_H
'            If First.dH > Second.dH Then
'               Return 1 * nDirection
'            ElseIf First.dH < Second.dH Then
'               Return -1 * nDirection
'            Else
'               Return 0
'            End If
'         Case COL_L
'            If First.dL > Second.dL Then
'               Return 1 * nDirection
'            ElseIf First.dL < Second.dL Then
'               Return -1 * nDirection
'            Else
'               Return 0
'            End If
'         Case COL_POSZ
'               'If First.posz > Second.dL Then
'               '   Return 1 * nDirection
'               'ElseIf First.dL < Second.dL Then
'               '   Return -1 * nDirection
'               'Else
'               '   Return 0
'               'End If
'         Case COL_MATERIAL
'            If First.sMATERIAL > Second.sMATERIAL Then
'               Return 1 * nDirection
'            ElseIf First.sMATERIAL < Second.sMATERIAL Then
'               Return -1 * nDirection
'            Else
'               Return 0
'            End If
'         Case COL_USAGE
'            If First.dUsage > Second.dUsage Then
'               Return 1 * nDirection
'            ElseIf First.dUsage < Second.dUsage Then
'               Return -1 * nDirection
'            Else
'               Return 0
'            End If
'         Case COL_WASTE
'            If First.dWaste > Second.dWaste Then
'               Return 1 * nDirection
'            ElseIf First.dWaste < Second.dWaste Then
'               Return -1 * nDirection
'            Else
'               Return 0
'            End If
'      End Select
'   End Function

'End Class
