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

Public Class ProdManagerVM
   Inherits VMBase

#Region "FIELDS & PROPERTIES"

   Private m_OpenProj_Timer As New DispatcherTimer
   Private m_bOpenProj As Boolean = False
   Private m_nProjIdToOpen As Integer = GDB_ID.NULL

   Private m_ProdManager_IsEnabled As Boolean = True
   Public ReadOnly Property ProdManager_IsEnabled As Boolean
      Get
         Return m_ProdManager_IsEnabled
      End Get
   End Property

   Private m_CurrProd As ProdFileVM
   Friend Property CurrProd As ProdFileVM
      Get
         Return m_CurrProd
      End Get
      Set(value As ProdFileVM)
         m_CurrProd = value
      End Set
   End Property

   Private m_TempCurrProd As ProdFileVM
   Friend Property TempCurrProd As ProdFileVM
      Get
         Return m_TempCurrProd
      End Get
      Set(value As ProdFileVM)
         m_TempCurrProd = value
      End Set
   End Property

   ' indice ultimo progetto
   Private m_nLastProdId As Integer
   Friend ReadOnly Property nLastProdId As Integer
      Get
         Return m_nLastProdId
      End Get
   End Property

   Public ReadOnly Property nProdType As BWType
      Get
         Return If(Not IsNothing(CurrProd), CurrProd.nType, BWType.NULL)
      End Get
   End Property

   Friend m_MruFiles As New MruList
   Public ReadOnly Property MruFileNames As ObservableCollection(Of String)
      Get
         Dim IdAndBTLFileNames As New ObservableCollection(Of String)
         For Each FileName In m_MruFiles.FileNames.ToList()
            Dim PdId As Integer = 0
            Dim sPdId As String = Path.GetFileNameWithoutExtension(DirectCast(FileName, String).Replace("__", "_"))
            Integer.TryParse(sPdId, PdId)
            Dim PdFileM = DbControllers.m_ProdController.FindCoreByProdId(PdId)
            If IsNothing(PdFileM) Then
               m_MruFiles.Remove(FileName)
            Else
               Dim PdFileVM = New ProdFileVM(PdFileM)
               IdAndBTLFileNames.Add(sPdId & " | " & PdFileVM.sBTLFileName)
            End If
         Next
         Return IdAndBTLFileNames
      End Get
   End Property

   Private m_GoToSupervisor_Visibility As Visibility
   Public ReadOnly Property GoToSupervisor_Visibility As Visibility
      Get
         Return m_GoToSupervisor_Visibility
      End Get
   End Property

   Private m_AddProj_Visibility As Visibility
   Public ReadOnly Property AddProj_Visibility As Visibility
      Get
         Return m_AddProj_Visibility
      End Get
   End Property

   ' Definizione comandi
   Private m_cmdOpen As ICommand
   Private m_cmdOpenMruFile As ICommand
   Private m_cmdSave As ICommand
   Private m_cmdAddProj As ICommand
   Private m_cmdGoToProj As ICommand
   Private m_cmdGoToSupervisor As ICommand

#Region "ToolTip"

   'Proprietà ToolTip
   Public ReadOnly Property OpenToolTip As String
      Get
         Return EgtMsg(MSG_TOPCOMMANDBAR + 2)
      End Get
   End Property
   Public ReadOnly Property SaveToolTip As String
      Get
         Return EgtMsg(MSG_TOPCOMMANDBAR + 3)
      End Get
   End Property
   Public ReadOnly Property AddProj_ToolTip As String
      Get
         Return EgtMsg(61921)
      End Get
   End Property
   Public ReadOnly Property GoToProj_ToolTip As String
      Get
         Return EgtMsg(61922)
      End Get
   End Property
   Public ReadOnly Property GoToSupervisor_ToolTip As String
      Get
         Return EgtMsg(61974)
      End Get
   End Property

#End Region ' ToolTip

#End Region    ' Fields & Properties

#Region "CONSTRUCTOR"

   Sub New()
      ' Creo riferimento a questa classe in Map
      Map.SetRefProdManagerVM(Me)
      ' abilito passaggio a supervisore
      If Map.refMainWindowVM.MainWindowM.GetKeyOption(KEY_OPT.SUPERVISOR) Then
         m_GoToSupervisor_Visibility = Visibility.Visible
      Else
         m_GoToSupervisor_Visibility = Visibility.Collapsed
      End If
      ' attivo bottone AddProj
      If GetMainPrivateProfileInt(S_GENERAL, K_ADDPROJ, 0) = 1 Then
         m_AddProj_Visibility = Visibility.Visible
      Else
         m_AddProj_Visibility = Visibility.Collapsed
      End If
      ' Leggo ultimo indice di progetto
      m_nLastProdId = GetMainPrivateProfileInt(S_GENERAL, K_PRODSINDEX, 1)
      ' Impostazioni MruLists
      m_MruFiles.Init(S_MRUPRODFILES, 8)
      ' imposto timer di apertura da ottimizzatore
      m_OpenProj_Timer.Interval = TimeSpan.FromMilliseconds(500)
      AddHandler m_OpenProj_Timer.Tick, AddressOf OpenProject_Tick
      m_OpenProj_Timer.Start()
   End Sub

#End Region    ' CONSTRUCTOR

#Region "METHODS"

   Friend Function InitNewProject(ByRef nProjId As Integer, ByRef nProdId As Integer, ByRef sProjectDir As String) As Boolean
      ' richiedo indice nuovo progetto
      nProdId = DbControllers.m_ProdController.GetNextIndex(nProjId, Map.refMainWindowVM.MainWindowM.GetKeyNumber())
      If nProdId <= 0 Then Return False
      sProjectDir = refMainWindowVM.MainWindowM.sProdsDir & "\" & nProdId.ToString("0000")
      ' creo cartella nuovo progetto
      If Not Directory.Exists(sProjectDir) Then
         Directory.CreateDirectory(sProjectDir)
      Else
         Dim di As System.IO.DirectoryInfo = New DirectoryInfo(sProjectDir)
         For Each file As FileInfo In di.EnumerateFiles()
            file.Delete()
         Next
         For Each dir As DirectoryInfo In di.EnumerateDirectories()
            dir.Delete(True)
         Next
      End If
      Return True
   End Function

   Public Function SetCurrProd(nProdId As Integer) As Boolean
      Dim CurrProdM As ProdFileM = DbControllers.m_ProdController.FindCoreByProdId(nProdId)
      If IsNothing(CurrProdM) Then Return False
      Map.refProdManagerVM.CurrProd = New ProdFileVM(CurrProdM)
      Return True
   End Function

   Public Sub ResetCurrProd()
      CurrProd = Nothing
   End Sub

   Friend Sub SetProdManagerIsEnabled(bIsEnabled As Boolean)
      m_ProdManager_IsEnabled = bIsEnabled
      NotifyPropertyChanged(NameOf(ProdManager_IsEnabled))
   End Sub

   Public Sub OpenProjectFromSupervisor(ProjIdToOpen As Integer)
      If (Not IsNothing(Map.refProdManagerVM.m_CurrProd) AndAlso ProjIdToOpen <> Map.refProdManagerVM.m_CurrProd.nProdId) OrElse Map.refMainMenuVM.SelPage <> Pages.MACHINING Then
         m_nProjIdToOpen = ProjIdToOpen
         m_bOpenProj = True
      End If
   End Sub

   Public Sub OpenProject_Tick()
      If Not m_bOpenProj Then Return
      m_bOpenProj = False
      Select Case Map.refMainMenuVM.SelPage
         Case Pages.MACHINING
            ' recupero progetto da Id 
            Dim DbProject As ProdFileM
            DbProject = DbControllers.m_ProdController.FindCoreByProdId(m_nProjIdToOpen)
            Dim ProjectVM As New ProdFileVM(DbProject)
            ' verifico se progetto modificato, e chiedo se salvare
            If Not ProjFileVM.VerifyProjectModification(Map.refProjManagerVM.CurrProj, ProjectType.PROJ) Then Return
            OpenProject(ProjectVM)
         Case Pages.VIEW
            ' verifico se progetto modificato, e chiedo se salvare
            If Not ProjFileVM.VerifyProjectModification(Map.refProjManagerVM.CurrProj, ProjectType.PROJ) Then Return
            LoadingWndHelper.OpenLoadingWnd(ActiveIds.GOTOPROD, 3, EgtMsg(63004), EgtMsg(63011), 10)          ' Optimization opening      ' Loading environment
            If Not IsNothing(Map.refProjManagerVM.CurrProj) AndAlso (m_nProjIdToOpen <> Map.refProjManagerVM.CurrProj.nProdId OrElse IsNothing(Map.refProdManagerVM.CurrProd)) Then
               Map.refProdManagerVM.SetCurrProd(m_nProjIdToOpen)
               Map.refProdManagerVM.CurrProd.SetReloadProject(True)
            Else
               Map.refProdManagerVM.CurrProd.SetReloadProject(False)
            End If
            ' Ricavo il tipo di Warehouse settato nell'INI
            Dim nDefault As Integer = 2
            If GetMainPrivateProfileInt(S_WAREHOUSE, EgtBEAMWALL.Core.ConstIni.K_TYPE, nDefault) = WarehouseType.MEDIUM Then
               ' Se di tipo Medium confronto le Sezioni del BTL importato con quelle in Warehouse
               WarehouseWndVM.UpdateSectionXMaterial()
            End If
            ' vado in pagina prod
            Map.refMainMenuVM.SetSelPage(Pages.MACHINING, False)
            ' aggiorno titolo
            Map.refMainWindowVM.UpdateTitle()
            LoadingWndHelper.CloseLoadingWnd(ActiveIds.GOTOPROD)
      End Select
      m_nProjIdToOpen = GDB_ID.NULL
   End Sub

#End Region    ' METHODS

#Region "COMMANDS"

#Region "OpenCommand"

   ''' <summary>
   ''' Returns a command that do Open.
   ''' </summary>
   Public ReadOnly Property OpenCommand As ICommand
      Get
         If m_cmdOpen Is Nothing Then
            m_cmdOpen = New Command(AddressOf Open)
         End If
         Return m_cmdOpen
      End Get
   End Property

   ''' <summary>
   ''' Execute the Open.  This method is invoked by the OpenCommand.
   ''' </summary>
   Friend Sub Open()
      ' verifico se progetto modificato, e chiedo se salvare
      If ProdFileVM.VerifyProjectModification(CurrProd) = MessageBoxResult.Cancel Then Return
      OpenProject(Nothing)
   End Sub

   Friend Sub OpenProject(TempCurrPd As ProdFileVM)
      m_TempCurrProd = TempCurrPd
      Dim sFilePath As String = ""
      ' se la string è vuota
      If IsNothing(TempCurrProd) Then
         If GetMainPrivateProfileInt(S_GENERAL, K_PROJECTMODE, 0) = 1 Then
            Dim OpenProdFileDialogVM As NewOpenProjectFileDialogVM = Nothing
            ' apro dialogo di scelta Prod
            OpenProdFileDialogVM = New NewOpenProjectFileDialogVM
            Dim OpenFile As New NewOpenProjectFileDialogV(Application.Current.MainWindow, OpenProdFileDialogVM)
            Dim DialogResult As Boolean? = OpenFile.EgtShowDialog(ProjectType.PROD)
            If IsNothing(DialogResult) OrElse Not DialogResult Then Return
            sFilePath = OpenProdFileDialogVM.SelProject.ProdFileVM.sProdPath
            m_TempCurrProd = OpenProdFileDialogVM.SelProject.ProdFileVM
         Else
            Dim OpenProjectFileDialogVM As OpenProjectFileDialogVM = Nothing
            ' apro dialogo di scelta file
            OpenProjectFileDialogVM = New OpenProjectFileDialogVM
            Dim OpenFile As New OpenProjectFileDialogV(Application.Current.MainWindow, OpenProjectFileDialogVM)
            Dim DialogResult As Boolean? = OpenFile.EgtShowDialog(ProjectType.PROD)
            If IsNothing(DialogResult) OrElse Not DialogResult Then Return
            sFilePath = OpenProjectFileDialogVM.SelProject.sProdPath
            TempCurrProd = OpenProjectFileDialogVM.SelProject
         End If
      Else
         sFilePath = If(Not IsNothing(TempCurrProd.sProdPath), TempCurrProd.sProdPath, "")
      End If
      LoadingWndHelper.OpenLoadingWnd(ActiveIds.OPENPROD, 3, EgtMsg(63004), EgtMsg(63001), 50)          ' Optimization opening     ' Loading project geometries
      If File.Exists(sFilePath) Then
         ' se la macchina del progetto in apertura non è tra le macchine disponibili lo segnalo e apro un progetto vuoto
         If IsNothing(Map.refMachinePanelVM.MachineList.FirstOrDefault(Function(x) x.Name = Map.refProdManagerVM.TempCurrProd.sMachine)) Then
            ' rimuovo il file in apertura dalla lista degli MRU
            Map.refProdManagerVM.m_MruFiles.Remove(sFilePath)
            MessageBox.Show(EgtMsg(61885), EgtMsg(10001), MessageBoxButton.OK, MessageBoxImage.Error)        'Error
            Map.refProjManagerVM.NewProject()
            Map.refProjectVM.MachGroupPanelVM = New MyMachGroupPanelVM(MyMachGroupPanelM.CreateMyMachGroupPanel(Map.refMachinePanelVM.MachineList.ToList()))
         Else
            If Map.refSceneHostVM.MainController.OpenProject(sFilePath, False) Then
               Map.refProjectVM.SetOptimizePanel_Visibility(True)
               Map.refTopPanelVM.UpdateQParameterVisibility()
               'SectionXMaterial.SetType(Map.refProjectVM.BTLStructureVM.nPROJTYPE)
               '' aggiorno le colonne in base al tipo progetto
               'Map.refRawPartListVM.UpdateColumns(Map.refProjectVM.BTLStructureVM.nPROJTYPE)
               'Map.refPartInRawPartListVM.UpdateColumns(Map.refProjectVM.BTLStructureVM.nPROJTYPE)
               'm_CurrProd = TempCurrProd
               'DbControllers.m_ProdController.LockByProdId(m_CurrProd.nProdId, True)
               '' carico lista macchine e macchina del progetto per il pulsante Reset Macchina del CALCPanel
               'Map.refCALCPanelVM.LoadMachineList()
               '' seleziono primo gruppo
               'Map.refProjectVM.MachGroupPanelVM.SelFirstMachGroup()
            End If
         End If
         ' imposto flag secondo tipo di progetto (travi o pareti)
         Dim sBTLFlag As String = If(TempCurrProd.nType = Core.ConstBeam.BWType.BEAM, K_BTLFLAG, K_WALLBTLFLAG)
         Dim nFlag As Integer = GetMainPrivateProfileInt(S_IMPORT, sBTLFlag, EIB_FL.TS3_POS + EIB_FL.SORT + EIB_FL.USEUATTR)
         EgtBeamSetFlag(nFlag)
      Else
         MessageBox.Show(EgtMsg(61871))
         Map.refSceneHostVM.MainController.NewProject()
         Map.refMainWindowVM.SetTitle("New - EgtBEAMWALL")
      End If
      ' aggiorno lista possibili nesting
      Map.refOptimizePanelVM.UpdateOriginTypeList(EgtGetFirstNameInGroup(GDB_ID.ROOT, "RawParts") <> GDB_ID.NULL)
      ' aggiorno visibilità bottone Muovi pezzi
      Map.refTopPanelVM.UpdateMovePartInRawPartVisibility()
      ' resetto eventuale visualizzazione statistiche
      Map.refInstrumentPanelVM.ResetStatisticsIsChecked()
      ' aggiorno titolo
      Map.refMainWindowVM.UpdateTitle()
      NotifyPropertyChanged(NameOf(MruFileNames))
      LoadingWndHelper.CloseLoadingWnd(ActiveIds.OPENPROD)
   End Sub

#End Region ' OpenCommand

#Region "OpenMruFileCommand"

   ''' <summary>
   ''' Returns a command that do Open.
   ''' </summary>
   Public ReadOnly Property OpenMruFileCommand As ICommand
      Get
         If m_cmdOpenMruFile Is Nothing Then
            m_cmdOpenMruFile = New Command(AddressOf OpenMruFile)
         End If
         Return m_cmdOpenMruFile
      End Get
   End Property

   ''' <summary>
   ''' Execute the Open.  This method is invoked by the OpenCommand.
   ''' </summary>
   Public Sub OpenMruFile(ByVal param As Object)
      ' verifico se progetto modificato, e chiedo se salvare
      If ProdFileVM.VerifyProjectModification(CurrProd) = MessageBoxResult.Cancel Then Return
      ' ricavo l'Id e il progetto associato per l'apertura di quest'ultimo
      Dim PdId As Integer = 0
      Dim arrStrPdId As String() = DirectCast(param, String).Split("|")
      Integer.TryParse(arrStrPdId(0), PdId)
      Dim PdFileM = DbControllers.m_ProdController.FindCoreByProdId(PdId)
      Dim PdFileVM = New ProdFileVM(PdFileM)
      OpenProject(PdFileVM)
   End Sub

#End Region ' OpenMruFileCommand

#Region "SaveCommand"

   ''' <summary>
   ''' Returns a command that do Save.
   ''' </summary>
   Public ReadOnly Property SaveCommand As ICommand
      Get
         If m_cmdSave Is Nothing Then
            m_cmdSave = New Command(AddressOf SaveCmd)
         End If
         Return m_cmdSave
      End Get
   End Property

   ''' <summary>
   ''' Execute the Save.  This method is invoked by the SaveCommand.
   ''' </summary>
   Public Sub SaveCmd()
      Save(True)
   End Sub

   Public Function Save(Optional bShowLoading As Boolean = False) As Boolean
      If IsNothing(m_CurrProd) Then Return False
      If bShowLoading Then LoadingWndHelper.OpenLoadingWnd(ActiveIds.SAVEPROD, 2, EgtMsg(63007), EgtMsg(63012), 70)          ' Project saving     ' Saving geometry
      Dim bOk As Boolean = Map.refSceneHostVM.SaveProject()
      If bShowLoading Then LoadingWndHelper.UpdateLoadingWnd(ActiveIds.SAVEPROD, 2, EgtMsg(63013), 70, 100)          ' Saving data on Db
      Dim MyMachGroupList As New List(Of MyMachGroupM)
      If Not IsNothing(Map.refProjectVM.MachGroupPanelVM) Then
         For Each MachGroup In Map.refProjectVM.MachGroupPanelVM.m_MyMachGroupPanelM.MachGroupMList
            MyMachGroupList.Add(MachGroup)
         Next
      End If
      ' aggiorno pezzi su Db
      If Not DbControllers.m_ProdController.UpdateMachGroup(CurrProd.nProdId, MyMachGroupList) And bShowLoading Then
         LoadingWndHelper.CloseLoadingWnd(ActiveIds.SAVEPROD)
         Return False
      End If
      ' verifico se Reset Macchina modificato e nel caso aggiorno DB e CurrProj
      If Map.refCALCPanelVM.IsMachineModified() Then
         DbControllers.m_ProdController.UpdateMachine(Map.refProdManagerVM.CurrProd.nProdId, Map.refCALCPanelVM.SelectedMachine.Name)
         Map.refProdManagerVM.CurrProd.SetMachine(Map.refCALCPanelVM.SelectedMachine.Name)
         ' ciclo sulla lista di ProjId associati
         For Each ProjId In Map.refProdManagerVM.CurrProd.nProjIdList
            ' aggiorno la Macchina per i ProjId associati sul DB
            DbControllers.m_ProjController.UpdateMachine(ProjId, Map.refCALCPanelVM.SelectedMachine.Name)
            ' se uno dei Proj interessati equivale al Proj correntemente aperto setto la Macchina dello stesso
            ' (poichè il progetto corrente non viene riaperto e riletto dal DB)
            If ProjId = Map.refProjManagerVM.CurrProj.nProjId Then Map.refProjManagerVM.CurrProj.SetMachine(Map.refCALCPanelVM.SelectedMachine.Name)
         Next
         Map.refCALCPanelVM.ResetMachineModified()
      End If
      ' se nuovo progetto
      If m_CurrProd.bIsNew Then
         ' resetto stato new
         ' DbControllers.m_ProdController.Reset(CurrProd.nProjId)
         m_CurrProd.bIsNew = False
      End If
      Map.refMainWindowVM.UpdateTitle()
      NotifyPropertyChanged(NameOf(MruFileNames))
      If bShowLoading Then LoadingWndHelper.CloseLoadingWnd(ActiveIds.SAVEPROD)
      Return bOk
   End Function

#End Region ' SaveCommand

#Region "AddProj"

   ''' <summary>
   ''' Returns a command that do Save.
   ''' </summary>
   Public ReadOnly Property AddProj_Command As ICommand
      Get
         If m_cmdAddProj Is Nothing Then
            m_cmdAddProj = New Command(AddressOf AddProj)
         End If
         Return m_cmdAddProj
      End Get
   End Property

   ''' <summary>
   ''' Execute the Save.  This method is invoked by the SaveCommand.
   ''' </summary>
   Public Sub AddProj()
      ' verifico se progetto modificato, e chiedo se salvare
      If IsNothing(CurrProd) Then Return
      Dim bNewProject As Boolean = False
      Dim sProjectDirPath As String = ""
      sProjectDirPath = CurrProd.sProdDirPath
      Dim VerifyResult As MessageBoxResult = MessageBoxResult.None
      ' verifico se progetto modificato, e chiedo se salvare
      If EgtGetModified() OrElse CurrProd.bIsNew OrElse Map.refCALCPanelVM.IsMachineModified() Then
         VerifyResult = MessageBox.Show(EgtMsg(61875), "", If(CurrProd.bIsNew, MessageBoxButton.OKCancel, MessageBoxButton.YesNoCancel), MessageBoxImage.Question)
         Select Case VerifyResult
            Case MessageBoxResult.Yes, MessageBoxResult.OK
               ' salvo proj
               Map.refProdManagerVM.Save()
            Case MessageBoxResult.Cancel
               Return
            Case Else   ' No
               EgtResetModified()
               OpenProject(CurrProd)
         End Select
      Else
         EgtResetModified()
      End If
      ' faccio scegliere proj da aggiungere
      Dim OpenProjectFileDialogVM As New OpenProjectFileDialogVM
      Dim ChooseProdFileDialog As New OpenProjectFileDialogV(Application.Current.MainWindow, OpenProjectFileDialogVM)
      Dim DialogResult As Boolean? = ChooseProdFileDialog.EgtShowDialog(ProjectType.PROJ, True)
      If IsNothing(DialogResult) OrElse Not DialogResult Then Return
      If IsNothing(OpenProjectFileDialogVM.SelProject.nProjId) OrElse OpenProjectFileDialogVM.SelProject.nProjId <= 0 Then Return
      ' verifico che il proj selezionato non abbia prod
      If Not IsNothing(OpenProjectFileDialogVM.SelProject.nProdId) AndAlso OpenProjectFileDialogVM.SelProject.nProdId > 0 Then
         ' verifico che non sia uno di quelli gia' collegati a questo Prod
         Dim bFound As Boolean = False
         For Each nProjId As Integer In CurrProd.nProjIdList
            If nProjId = OpenProjectFileDialogVM.SelProject.nProjId Then
               bFound = True
               Exit For
            End If
         Next
         If bFound Then
            MessageBox.Show("Selezionato progetto che fa gia' parte di questa produzione!", "Errore", MessageBoxButton.OK, MessageBoxImage.Error)
         Else
            MessageBox.Show("Progetto gia' collegato ad una produzione!", "Errore", MessageBoxButton.OK, MessageBoxImage.Error)
         End If
         Return
      End If
      ' verifico che sia associato alla stessa macchina
      If OpenProjectFileDialogVM.SelProject.sMachine <> CurrProd.sMachine Then
         MessageBox.Show("Progetto per una macchina diversa da quella del progetto corrente!", "Errore", MessageBoxButton.OK, MessageBoxImage.Error)
         Return
      End If
      ' inserisco proj nel prod corrente
      Dim bOk As Boolean = EgtInsertFile(OpenProjectFileDialogVM.SelProject.sProjPath)
      ' lo salvo
      bOk = bOk AndAlso Save(False)
      If bOk Then
         ' riporto aggiunta proj a prod su Db
         DbControllers.m_ProdController.AddProj(CurrProd.nProdId, OpenProjectFileDialogVM.SelProject.nProjId)
      End If
      ' Ricavo il tipo di Warehouse settato nell'INI
      Dim nDefault As Integer = 2
      If GetMainPrivateProfileInt(S_WAREHOUSE, EgtBEAMWALL.Core.ConstIni.K_TYPE, nDefault) = WarehouseType.MEDIUM Then
         ' Se di tipo Medium confronto le Sezioni del BTL importato con quelle in Warehouse
         WarehouseWndVM.UpdateSectionXMaterial()
      End If
      ' aggiorno CurrProd
      Dim PdFileM = DbControllers.m_ProdController.FindCoreByProdId(CurrProd.nProdId)
      CurrProd.ProdFileM.SetProjIdList(PdFileM.nProjIdList)
      ' ricarico BTLPartList
      OpenProject(CurrProd)
   End Sub


#End Region ' AddProj

#Region "GoToProj"

   ''' <summary>
   ''' Returns a command that do Open.
   ''' </summary>
   Public ReadOnly Property GoToProj_Command As ICommand
      Get
         If m_cmdGoToProj Is Nothing Then
            m_cmdGoToProj = New Command(AddressOf GoToProj)
         End If
         Return m_cmdGoToProj
      End Get
   End Property

   ''' <summary>
   ''' Execute the Open.  This method is invoked by the OpenCommand.
   ''' </summary>
   Friend Sub GoToProj()
      If IsNothing(m_CurrProd) Then Return
      ' recupero Proj associati da Db
      Dim ProjFileMList As List(Of ProjFileM) = DbControllers.m_ProjController.GetByProdAsc(m_CurrProd.nProdId)
      Dim nProjId As Integer = 0
      ' verifico se salvare progetto corrente
      Dim VerifyResult As MessageBoxResult = ProdFileVM.VerifyProjectModification(Map.refProdManagerVM.CurrProd)
      If VerifyResult = MessageBoxResult.Cancel Then Return
      ' se piu' di uno
      If IsNothing(ProjFileMList) Then
         Return
      ElseIf ProjFileMList.Count = 1 AndAlso ProjFileMList(0).nProjId > 0 Then
         LoadingWndHelper.OpenLoadingWnd(ActiveIds.GOTOPROJ, 2, EgtMsg(63015), EgtMsg(63011), 10)          ' Part viewer opening     ' Loading environment
         nProjId = ProjFileMList(0).nProjId
      ElseIf ProjFileMList.Count > 1 Then
         Dim ProjFileVMList As New List(Of ProjectFileVM)
         For Each Project In ProjFileMList
            ProjFileVMList.Add(New ProjFileVM(Project))
         Next
         ' apro finestra di scelta
         Dim OpenProjectFileDialogVM As New OpenProjectFileDialogVM
         Dim ChooseProjFileDialog As New OpenProjectFileDialogV(Application.Current.MainWindow, OpenProjectFileDialogVM)
         Dim DialogResult As Boolean? = ChooseProjFileDialog.EgtShowDialog(ProjectType.PROJ, ProjFileVMList)
         If IsNothing(DialogResult) OrElse Not DialogResult Then Return
         ' se proj selezionato
         If Not IsNothing(OpenProjectFileDialogVM.SelProject.nProdId) AndAlso OpenProjectFileDialogVM.SelProject.nProdId > 0 Then
            nProjId = OpenProjectFileDialogVM.SelProject.nProjId
         End If
         LoadingWndHelper.OpenLoadingWnd(ActiveIds.GOTOPROJ, 2, EgtMsg(63015), EgtMsg(63011), 10)          ' Part viewer opening     ' Loading environment
      Else Return
      End If
      ' apro progetto proj
      Map.refProjManagerVM.SetCurrProj(nProjId)
      ' ricarico progetto se il prod e' nullo (quindi e' stato cancellato)
      Map.refProjManagerVM.CurrProj.SetReloadProject(IsNothing(CurrProd) OrElse VerifyResult = MessageBoxResult.No)
      ' vado in pagina proj
      Map.refMainMenuVM.SetSelPage(Pages.VIEW, False)
      LoadingWndHelper.CloseLoadingWnd(ActiveIds.GOTOPROJ)
   End Sub

#End Region ' GoToProj

#Region "GoToSupervisor"

   ''' <summary>
   ''' Returns a command that do Open.
   ''' </summary>
   Public ReadOnly Property GoToSupervisor_Command As ICommand
      Get
         If m_cmdGoToSupervisor Is Nothing Then
            m_cmdGoToSupervisor = New Command(AddressOf GoToSupervisor)
         End If
         Return m_cmdGoToSupervisor
      End Get
   End Property

   ''' <summary>
   ''' Execute the Open.  This method is invoked by the OpenCommand.
   ''' </summary>
   Friend Sub GoToSupervisor()
      If IsNothing(m_CurrProd) Then Return
      ' apro supervisore
      Dim sSupervisorName As String = "EgtBEAMWALL.SupervisorR32"
      ' recupero processo del supervisore
      Dim localProc As Process() = Process.GetProcessesByName(sSupervisorName)
      If localProc.Length > 0 Then
         For Each p As Process In localProc
            ' porto in primo piano il Supervisor
            BringWindowToFront(p.MainWindowHandle)
            Exit For
         Next
      Else
         Dim sSupervisorPath As String = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory) & "\" & sSupervisorName & ".exe"
         Try
            Process.Start(sSupervisorPath, "1 " & CurrProd.nProdId)
         Catch ex As Exception
            EgtOutLog("Error: impossible starting supervisor from path " & sSupervisorPath)
         End Try
      End If
      ' mando richiesta di apertura progetto in supervisore
      'Dim x = DbControllers.m_StatusMapController.GetProd
      DbControllers.m_StatusMapController.UpdateAction(DbControllers.m_SupervisorId, Map.refProdManagerVM.CurrProd.nProdId, Map.refProdManagerVM.CurrProd.nProdId, StatusMapItemType.Comm, StatusMapOpType.ChangeProdInSupervisorRequest, "")
   End Sub

#End Region ' GoToSupervisor

#End Region    ' Commands

End Class
