Imports System.Collections.ObjectModel
Imports EgtUILib

Public Class Polishing

   ' Riferimenti a pagine
   Private m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
   Private WithEvents m_CurrProjPage As CurrentProjectPageUC
   ' Flag di pagina attiva
   Private m_bActive As Boolean = False
   ' Flag di simulazione in corso
   Private m_bSimul As Boolean = False

   ' Origine tavola e dati grezzo
   Private m_bRawOk As Boolean = False
   Private m_ptTabOri As Point3d
   Private m_ptRawMin As Point3d
   Private m_ptRawMax As Point3d
   ' Parametri della lavorazione
   Private m_bPoliOk As Boolean = False
   ' Lista dei kit di lucidatura disponibili
   Private m_KitList As New ObservableCollection(Of String)

   Private Sub Polishing_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
      ' assegno messaggi
      SimulBtn.ToolTip = EgtMsg(MSG_CADCUTPAGEUC + 1)
      OkBtn.ToolTip = EgtMsg(MSG_DIRECTCUTPAGEUC + 30)
   End Sub

   Private Sub Polishing_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
      ' Attivo la pagina
      m_CurrProjPage = m_MainWindow.m_CurrentProjectPageUC
      m_bActive = True
      ' Se rientro da simulazione
      If m_bSimul Then
         m_bSimul = False
         ' Disabilito registrazione progetto modificato
         EgtDisableModified()
         ' Aggiorno visualizzazione
         ShowAllCurrPhaseMachinings()
         m_MainWindow.m_DirectCutPageUC.m_bShowMachine = True
         EgtSetMachineLook(m_MainWindow.m_DirectCutPageUC.m_nMachLook)
         EgtDraw()
         Return
      End If
      ' Disabilito registrazione progetto modificato
      EgtDisableModified()
      ' Carico i kit di lucidatura disponibili
      ReadKitList()
      ' Associo la lista dei kit alla combobox
      PolishingCmBx.ItemsSource = m_KitList
      ' Rendo corrente ultima lucidatura scelta, altrimenti la prima della lista
      If m_KitList.Count > 0 Then
         Dim sLastPolishing As String = ""
         GetPrivateProfileString( S_DIRECTCUTS, K_DC_POLISH_NAME, m_KitList( 0), sLastPolishing, m_MainWindow.GetIniFile())
         PolishingCmBx.SelectedItem = sLastPolishing
         If PolishingCmBx.SelectedIndex < 0 Then PolishingCmBx.SelectedIndex = 0
      End If
      ' Se non c'è kit selezionato, disabilito simulazione ed esecuzione
      If PolishingCmBx.SelectedIndex < 0 Then
         m_bPoliOk = False
         UpdateSimulOkBtn()
      End If 
      ' Rendo semitrasparente il grezzo
      Dim nRawSolidId = EgtGetFirstNameInGroup(m_CurrProjPage.m_nRawId, NAME_RAW_SOLID)
      EgtSetAlpha( nRawSolidId, 60)
      ' Aggiorno visualizzazione
      EgtDraw()
   End Sub

   Friend Sub Polishing_Unloaded(sender As Object, e As RoutedEventArgs) Handles Me.Unloaded
      ' Se non vado in simulazione
      If Not m_bSimul Then
         ' Dichiaro sottopagina da non riattivare
         m_MainWindow.m_DirectCutPageUC.m_ActiveDirectCutPage = DirectCutPageUC.DirectCutPages.DirectCut
         ' Cancello eventuali lucidature
         RemovePolishings()
         ' Riattivo eventuali lavorazioni presenti
         ActivateAllMachinings()
         ' Abilito registrazione progetto modificato
         EgtEnableModified()
         ' Nascondo la macchina
         m_MainWindow.m_DirectCutPageUC.m_bShowMachine = False
         EgtSetMachineLook(MCH_LOOK.TAB)
         ' Ripristino opacità del grezzo
         Dim nRawSolidId = EgtGetFirstNameInGroup(m_CurrProjPage.m_nRawId, NAME_RAW_SOLID)
         EgtSetAlpha( nRawSolidId, 100)
         ' Aggiorno visualizzazione
         EgtDraw()
      End If
      ' Dichiaro pagina non attiva
      m_bActive = False
   End Sub

   Private Sub ReadKitList()
      ' Pulisco
      m_KitList.Clear()
      ' Leggo
      Dim nKitIndex As Integer = 1
      Dim sKitName As String = ""
      Dim sKitFile As String = m_MainWindow.GetKitsFile()
      While ReadKitName( nKitIndex, sKitFile, sKitName)
         m_KitList.Add( sKitName)
         nKitIndex += 1
      End While
   End Sub

   Private Function ReadKitName( nKitIndex As Integer, sKitFile As String, ByRef sKitName As String) As boolean
      ' Leggo il nome del kit
      Dim sKey As String = K_KIT & nKitIndex.ToString("D2")
      Return ( GetPrivateProfileString( S_HEADER, sKey, "", sKitName, sKitFile) > 0)
   End Function

   Private Sub UpdateSimulOkBtn()
      If m_bPoliOk Then
         SimulBtn.IsEnabled = True
         SimulBtn.Foreground = Brushes.Black
         OkBtn.IsEnabled = True
         OkBtn.Foreground = Brushes.Black
      Else
         SimulBtn.IsEnabled = False
         SimulBtn.Foreground = Brushes.DarkGray
         OkBtn.IsEnabled = False
         OkBtn.Foreground = Brushes.DarkGray
      End If
   End Sub

   Private Sub TypeCmBx_SelectionChanged(sender As Object, e As EventArgs) Handles PolishingCmBx.SelectionChanged
      Dim nIndex As String = PolishingCmBx.SelectedIndex
      If nIndex < 0 Then Return
      Dim sKitName As String = m_KitList( nIndex)
      WritePrivateProfileString( S_DIRECTCUTS, K_DC_POLISH_NAME, sKitName, m_MainWindow.GetIniFile())
      ' Calcolo la lucidatura
      CreatePolishing( sKitName)
      ' Aggiornamenti interfaccia utente e grafica
      UpdateSimulOkBtn()
      EgtDraw()
   End Sub

   Private Sub SimulBtn_Click(sender As Object, e As RoutedEventArgs) Handles SimulBtn.Click
      ' Verifico ci sia una lucidatura valida
      If Not m_bPoliOk Then Return
      ' Salvo il progetto con le lavorazioni
      EgtSetCurrentContext(m_CurrProjPage.CurrentProjectScene.GetCtx())
      Dim sMchPath As String = m_MainWindow.GetTempDir() & "\" & "DirectProj.nge"
      m_MainWindow.m_CurrentProjectPageUC.SaveFile(sMchPath, False)
      ' Predispongo passaggio a simulazione
      m_bSimul = True
      m_CurrProjPage.m_SceneButtons.MeasureBtn.IsChecked = False
      m_CurrProjPage.CurrProjGrid.Visibility = Windows.Visibility.Hidden
      m_CurrProjPage.CurrentProjectPageGrid.Children.Remove(m_MainWindow.m_DirectCutPageUC)
      m_MainWindow.m_PrevActivePage = MainWindow.Pages.DirectCut
      m_CurrProjPage.CurrentProjectPageGrid.Children.Add(m_MainWindow.m_SimulationPage)
      m_MainWindow.m_ActivePage = MainWindow.Pages.Simulation
   End Sub

   Private Sub OkBtn_Click(sender As Object, e As RoutedEventArgs) Handles OkBtn.Click
#If TRIAL Then
      m_CurrProjPage.SetWarningMessage("Trial Version")
#Else
      ' Verifico non sia versione Ufficio
      If m_MainWindow.GetKeyOption( MainWindow.KEY_OPT.OFFICE_TYPE) Then
          m_CurrProjPage.SetWarningMessage( "Office Version")
          Return
      End If
      ' Verifico ci sia una lucidatura valida
      If Not m_bPoliOk Then Return
      ' Salvo il progetto con le lavorazioni
      Dim sMchPath As String = m_MainWindow.GetTempDir() & "\" & "DirectProj.nge"
      m_MainWindow.m_CurrentProjectPageUC.SaveFile(sMchPath, False)
      ' Genero file CNC (lancio anche se errore in precedenza)
      Dim sCncPath As String = m_MainWindow.GetCncDir() & "\DirectCut" & m_MainWindow.m_CurrentMachine.sIsoFileExt
      Dim bOk As Boolean = EgtGenerate(sCncPath, "OmagCut ver." & m_MainWindow.GetVersion())
      ' Se errore in generazione, segnalo l'errore ed esco
      If Not bOk Then
         m_CurrProjPage.SetErrorMessage(EgtMsg(90314))       'Errore nella generazione del programma CN
         Return
      End If
      ' Download programma (eventuali errori sono segnalati dalla funzione)
      If m_MainWindow.m_CNCommunication.SendProgram(sCncPath, 900) Then
         ' copio il progetto corrente come progetto in lavorazione
         Dim sWrkPath As String = m_MainWindow.GetTempDir() & "\" & "WorkProj.nge"
         My.Computer.FileSystem.CopyFile(sMchPath, sWrkPath, True)
         ' lancio eventuale lua post-trasmissione
         m_MainWindow.ExecSentProgScript( True)
      End If
#End If
   End Sub

   Private Sub ExitBtn_Click(sender As Object, e As RoutedEventArgs) Handles ExitBtn.Click
      m_MainWindow.m_DirectCutPageUC.LeftButtonGrid.Children.Remove(Me)
   End Sub

   Private Function CreatePolishing( sKitName As String) As Boolean
      ' Verifico sia definita la lucidatura
      If String.IsNullOrWhiteSpace( sKitName) Then
         m_bPoliOk = False
         Return False
      End If
      ' Disattivo eventuali lavorazioni presenti
      DeactivateAllMachinings()
      ' Cancello eventuali precedenti lucidature
      RemovePolishings()
      ' Creo la lavorazione
      Dim nKerfId As Integer = EgtGetFirstNameInGroup( m_CurrProjPage.m_nRawId, NAME_KERF)
      m_bPoliOk = AddPolishings( sKitName, nKerfId)
      EgtSetCurrPhase( 1)
      Return m_bPoliOk
   End Function

End Class