Imports System.Collections.ObjectModel
Imports EgtUILib
Imports EgtWPFLib5
Imports EgtBEAMWALL.Core
Imports System.IO
Imports System.Text.RegularExpressions

Public Module CurrentMachine

   Enum FlowTypes As Integer
      ONEBYONE = 1
      CONTINUOUS = 2
   End Enum

   Enum MsgParagraphs As Integer
      MDI = 1
      PLC = 2
      CNC = 3
      INPUT = 4
      OUTPUT = 5
   End Enum

   ' Nome macchina corrente
   Private m_sMachineName As String = String.Empty
   ' Direttorio macchina corrente
   Private m_sMachDir As String = String.Empty
   ' File ini della macchina
   Private m_sMachIniFile As String = String.Empty
   ' File ini dei parametri macchina
   Private m_sMachParamIniFile As String = String.Empty
   ' Cartella degli script
   Private m_sMachScriptDir As String = String.Empty
   ' Ffile dei messaggi macchina
   Private m_sMachMessagesFile As String = String.Empty

   ' Tipo macchina
   Private m_nType As MachineType

   ' Per macchine pareti:
   ' Posizione vista
   Private m_nViewDir As VT
   Public ReadOnly Property ViewDir As VT
      Get
         Return m_nViewDir
      End Get
   End Property

   Friend ReadOnly Property nType As MachineType
      Get
         Return m_nType
      End Get
   End Property

   ' tipo di CN della macchina
   Private m_NCType As NCTypes = NCTypes.NULL
   Public ReadOnly Property NCType As Integer
      Get
         Return m_NCType
      End Get
   End Property

   Private m_Flow As FlowTypes = FlowTypes.ONEBYONE
   Friend ReadOnly Property Flow As FlowTypes
      Get
         Return m_Flow
      End Get
   End Property

#Region "Proprietà che leggono e scrivono i valori anche da o su file ini"

   Friend ReadOnly Property sMachineName As String
      Get
         Return m_sMachineName
      End Get
   End Property

   Friend ReadOnly Property sMachDir As String
      Get
         Return m_sMachDir
      End Get
   End Property

   Friend ReadOnly Property sMachIniFile As String
      Get
         Return m_sMachIniFile
      End Get
   End Property

   Friend ReadOnly Property sMachParamIniFile As String
      Get
         Return m_sMachParamIniFile
      End Get
   End Property

#End Region

   'Private m_MachTableList As New ObservableCollection(Of MachTable)
   'Public Property MachTableList As ObservableCollection(Of MachTable)
   '   Get
   '      Return m_MachTableList
   '   End Get
   '   Set(value As ObservableCollection(Of MachTable))
   '      m_MachTableList = value
   '   End Set
   'End Property

#Region "Init"

   Sub InitCurrentMachine(sMachinesRootDir As String, sMachineName As String, nMachineType As MachineType)
      ' Nome macchina corrente
      m_sMachineName = sMachineName
      ' Impostazione direttorio macchina
      m_sMachDir = sMachinesRootDir & "\" & sMachineName
      ' Impostazione path MachIni file
      m_sMachIniFile = sMachinesRootDir & "\" & sMachineName & "\" & sMachineName & ".ini"

      ' Leggo lingua corrente
      Dim sLanguage As String = String.Empty
      GetMainPrivateProfileString(S_GENERAL, K_MESSAGES, "", sLanguage)
      ' Recupero nome file dei messaggi della lingua corrente
      Dim sMsgName As String = ".txt"
      Dim nIndex As Integer = 1
      While True
         Dim ReadLanguage As Language = GetPrivateProfileLanguage(S_LANGUAGES, K_LANGUAGE & nIndex, m_sMachIniFile)
         If IsNothing(ReadLanguage) Then Exit While
         If String.Compare(ReadLanguage.Name, sLanguage, True) = 0 Then
            sMsgName = ReadLanguage.FilePath
            Exit While
         End If
         nIndex += 1
      End While
      ' Leggo file messaggi
      m_sMachMessagesFile = m_sMachDir & "\" & "Messages" & "\" & sMsgName
      ' Leggo attivazione messaggi Cn/Plc
      Map.refMachCommandMessagePanelVM.bMsgTranslationActive = GetPrivateProfileInt(S_LANGUAGES, K_ENABLE, 0, m_sMachIniFile)
      ' Impostazione tipo macchina
      m_nType = nMachineType
      ' Impostazione path MachParamIni file
      If nType = MachineType.BEAM Then
         m_sMachParamIniFile = sMachinesRootDir & "\" & sMachineName & "\" & K_BEAM & "\" & MACH_INI_FILE_NAME
      ElseIf nType = MachineType.WALL Then
         m_sMachParamIniFile = sMachinesRootDir & "\" & sMachineName & "\" & K_WALL & "\" & MACH_INI_FILE_NAME
      Else
         ' Se macchina di tipo BOTH prendo quello presente in Beam, se esiste, altrimenti prendo quello in Wall
         Dim sBeamMachParamIniFile = sMachinesRootDir & "\" & sMachineName & "\" & K_BEAM & "\" & MACH_INI_FILE_NAME
         Dim sWallMachParamIniFile = sMachinesRootDir & "\" & sMachineName & "\" & K_WALL & "\" & MACH_INI_FILE_NAME
         If nType = MachineType.BOTH Then
            m_sMachParamIniFile = If(File.Exists(sBeamMachParamIniFile), sBeamMachParamIniFile, sWallMachParamIniFile)
         End If
      End If

      ' leggo tipo di avanzamento pezzi
      m_Flow = GetPrivateProfileInt(S_GENERAL, K_FLOW, 1, m_sMachIniFile)
      ' Impostazione path Script dir
      m_sMachScriptDir = sMachinesRootDir & "\" & sMachineName & "\" & K_SCRIPT

      ' crea l'elenco dei parametri della macchina corrente
      CreateMachParams()

      ' recupero tipo di controllo
      m_NCType = GetPrivateProfileInt(S_GENERAL, K_NCTYPE, 1, m_sMachIniFile)

      ' inizializzo assi
      Map.refAxesPanelVM.LoadAxes()

      ' imposto visibilita' input output
      Map.refMainMenuVM.SetInputOutputVisibility()
      ' leggo parametri macchina da WallData
      If nType = MachineType.BEAM Then
         ' Assegno i dati
         EgtLuaCreateGlobTable("GWD")
         EgtLuaSetGlobStringVar("GWD.BASEDIR", Map.refMainWindowVM.MainWindowM.sBeamRoot)
         EgtLuaSetGlobStringVar("GWD.MACHINE", m_sMachineName)
         ' Eseguo lo script
         Dim sExecPath As String = Map.refMainWindowVM.MainWindowM.sBeamRoot & "\" & GETBEAMDATA_FILE_NAME
         Dim bOk As Boolean = False
         If EgtLuaExecFile(sExecPath) Then
            ' Recupero i risultati
            Dim nErr As Integer = 999
            EgtLuaGetGlobIntVar("GWD.ERR", nErr)
            bOk = (nErr = 0)
            If Not bOk Then EgtOutLog("GetBeamData Err=" & nErr.ToString())
         Else
            bOk = False
            EgtOutLog("Error executing GetBeamData script " & sExecPath)
         End If
         If bOk Then
            Dim nTemp As Integer
            EgtLuaGetGlobIntVar("GWD.SIMUL_VIEW_DIR", nTemp)
            Select Case nTemp
               Case 0
                  m_nViewDir = VT.ISO_SW
               Case 1
                  m_nViewDir = VT.ISO_NW
               Case 2
                  m_nViewDir = VT.ISO_SW
               Case 3
                  m_nViewDir = VT.ISO_NE
               Case 4
                  m_nViewDir = VT.ISO_SE
            End Select
         Else
            m_nViewDir = VT.ISO_SW
         End If
         ' Cancello tavola globale
         EgtLuaResetGlobVar("GWD")
         ' aggiorno parametro in gestore viste
         Core.ViewPanelVM.UpdateMachParam(m_nViewDir)
      End If
      If nType = MachineType.WALL Then
         ' Assegno i dati
         EgtLuaCreateGlobTable("GWD")
         EgtLuaSetGlobStringVar("GWD.BASEDIR", Map.refMainWindowVM.MainWindowM.sWallRoot)
         EgtLuaSetGlobStringVar("GWD.MACHINE", m_sMachineName)
         ' Eseguo lo script
         Dim sExecPath As String = Map.refMainWindowVM.MainWindowM.sWallRoot & "\" & GETWALLDATA_FILE_NAME
         Dim bOk As Boolean = False
         If EgtLuaExecFile(sExecPath) Then
            ' Recupero i risultati
            Dim nErr As Integer = 999
            EgtLuaGetGlobIntVar("GWD.ERR", nErr)
            bOk = (nErr = 0)
            If Not bOk Then EgtOutLog("GetWallData Err=" & nErr.ToString())
         Else
            bOk = False
            EgtOutLog("Error executing GetWallData script " & sExecPath)
         End If
         If bOk Then
            Dim nTemp As Integer
            EgtLuaGetGlobIntVar("GWD.SIMUL_VIEW_DIR", nTemp)
            Select Case nTemp
               Case 1
                  m_nViewDir = VT.ISO_NW
               Case 2
                  m_nViewDir = VT.ISO_SW
               Case 3
                  m_nViewDir = VT.ISO_NE
               Case 4
                  m_nViewDir = VT.ISO_SE
            End Select
         End If
         ' Cancello tavola globale
         EgtLuaResetGlobVar("GWD")
         ' aggiorno parametro in gestore viste
         Core.ViewPanelVM.UpdateMachParam(m_nViewDir)
      End If
      ' se axium
      If NCType = NCTypes.NUM_AXIUM_APSERVER OrElse NCType = NCTypes.NUM_AXIUM_PCTOOLKIT Then
         ' verifico se il file messaggi macchina è da aggiornare
         Dim sFromMachine As String = sMachinesRootDir & "\" & sMachineName & "\Messages\" & "FromMachine_" & sMsgName
         If File.Exists(sFromMachine) Then
            ' se file messaggi macchina piu' nuovo
            If File.GetLastWriteTime(sFromMachine) > File.GetLastWriteTime(m_sMachMessagesFile) Then
               ' aggiorno il file
               Dim FromMachineLines() As String = File.ReadAllLines(sFromMachine)
               For Each sLine In FromMachineLines
                  Dim Value As Match = Regex.Match(sLine, "N(\d*)\s*\$\d*:(.*)$")
                  If Not IsNothing(Value) AndAlso Value.Groups.Count >= 2 AndAlso Not IsNothing(Value.Groups(0)) AndAlso Not IsNothing(Value.Groups(1)) Then
                     WritePrivateProfileString("PLC", Value.Groups(1).Value, Value.Groups(2).Value, m_sMachMessagesFile)
                  End If
               Next
            End If
         End If
      End If
      ' inizializzo stati e modi
      Map.refLeftPanelVM.LoadChannels()
      Map.refLeftPanelVM.LoadOPStates()
      Map.refLeftPanelVM.LoadOPModes()
      ' Imposto visibilità variabili E80000
      Map.refLeftPanelVM.SetE80000Visibility()
   End Sub

#End Region 'Init

#Region "Methods"

   ' funzione che crea l'elenco dei parametri Macchina
   Friend Sub CreateMachParams()
      'MachTableList.Clear()
      'Dim NewMachParam As MachParam = Nothing
      'Dim MachParamList As New ObservableCollection(Of MachParam)
      'Dim TableIndex = 1
      'Dim ParamIndex As Integer = 1
      'Dim TableName As String = String.Empty
      '' verifico che ci sia una table con l'indice designato e ne leggo il nome
      'While GetMachPrivateProfileString(TableIndex, K_NAME, "", TableName)
      '   ' leggo tutti i parametri della table
      '   While MachParamIniFile.GetMachPrivateProfileParam(TableIndex, ParamIndex, NewMachParam)
      '      MachParamList.Add(NewMachParam)
      '      ParamIndex += 1
      '   End While
      '   MachTableList.Add(New MachTable(TableName, MachParamList))
      '   ' aggiorno indici e resetto lista per lettura dell'eventuale table successiva
      '   TableIndex += 1
      '   ParamIndex = 1
      '   MachParamList = New ObservableCollection(Of MachParam)
      'End While
   End Sub

   Public Function MachMsg(Paragraph As MsgParagraphs, nId As Integer) As String
      Dim sMsg As String = ""
      Dim sPar As String = ""
      Select Case Paragraph
         Case MsgParagraphs.MDI
            sPar = MDI_MSG
         Case MsgParagraphs.PLC
            sPar = PLC_MSG
         Case MsgParagraphs.CNC
            sPar = CNC_MSG
         Case MsgParagraphs.INPUT
            sPar = INPUT_MSG
         Case MsgParagraphs.OUTPUT
            sPar = OUTPUT_MSG
      End Select
      EgtGetStringUtf8FromIni(sPar, nId, nId, sMsg, m_sMachMessagesFile)
      Return sMsg
   End Function

#End Region 'Methods

End Module
