Option Strict On
Option Explicit On

Imports System.Globalization
Imports System.IO
Imports System.Threading
Imports IntraSell_DLL
Imports IntraSell_Net_Base
Imports IntraSell_Net_Starter

Public Module ModuleSetup
    Const SETUP_DRIVE As String = "C:\"

    Public Const MYSQL_PROCESS_NAME As String = SETUP_DRIVE & "MySQL Server 5.1\startup.bat"
    Public Const MYSQL_INTRASELL_BATCH_INSTALL As String = SETUP_DRIVE & "MySQL Server 5.1\\install.bat"
    Public INTRASELL_FOLDER As String = ClassSettings.GetDataPath() 'SETUP_DRIVE & "IntraSell_Net"
    Public VORLAGEN_FOLDER As String = INTRASELL_FOLDER & "\Vorlagen"


    Private Function GetDownloadPath() As String
        Return GetAppPath()
    End Function

    ''' <summary>
    ''' Startet eine mySQL Server instanz
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function StartMySQLServer() As Boolean
        Try
            'Start MySQL Process 
            If File.Exists(MYSQL_PROCESS_NAME) Then
                Shell(MYSQL_PROCESS_NAME, AppWinStyle.Hide, Wait:=True, Timeout:=30)
                Thread.Sleep(3 * 1000)
            Else
                Dim msg = String.Format(Messages.ModuleSetup_MySQL_fehlt, MYSQL_PROCESS_NAME)
                Throw New Exception(msg)
            End If
        Catch ex1 As Exception
            Dim lesbareMeldung As String = Messages.Setup_MySQL_Datenbank_nicht_gefunden & vbNewLine & ex1.Message
            If MsgBox(lesbareMeldung, vbYesNo, Messages.Setup_MySQL_Datenbank_fehlt) = vbYes Then
                Main.Cursor = Cursors.WaitCursor
                Setup.Show()
                SetUpMySqlServer(silent:=True)
                Setup.Close()
                Main.Cursor = Cursors.Default
            Else
                MsgBox(Messages.Setup_MySQL_Konfigurieren, vbInformation)
                Setup.ShowDialog()
            End If
        End Try
        Return ConnectionOK()
    End Function


    ''' <summary>
    ''' Set Up new MySQL Server instance
    ''' START 
    ''' ASK User if Sure 
    ''' Download File from Repo 
    ''' Extract Files for MySQL Server 
    ''' Start MySQL Process 
    ''' Check if Connection is possible 
    ''' DONE
    ''' </summary>
    ''' <param name="silent"></param>
    ''' <returns>True if Setup OK</returns>
    ''' <remarks></remarks>
    Function SetUpMySqlServer(Optional silent As Boolean = False) As Boolean
        SetUpMySqlServer = False
        'START
        WriteLog("Setup MySQL START")
        Try
            WriteLog("Check connection ...") 'First Check if MySQL already running 
            Dim gotConnection As Boolean = VarValue_Default("ADMIN", "WebShop") = "WebShop"
            If gotConnection Then
                Dim msg As String = Messages.Setup_MySQL_Ok
                WriteLog(msg)
                If Not silent Then
                    UserMessagePopUp("Datenbank", msg, vbInformation)
                End If
                Return True
            End If
        Catch ex As Exception
            'continue 
        End Try

        Dim achtung = UserMessagePopUp("Datenbank", "Datenbank wird vorbereitet. Bitte warten.", MsgBoxStyle.Information)

        'Extract Files for MySQL Server 
        Dim mySqlZIP As String = GetDownloadPath() + "MySQL Server 5.1.zip"
        'Download File from Repo 

        'nicht herunterladen falls die Datei existiert 
        If Not File.Exists(mySqlZIP) Then
            Dim logMsg = $"Herunterlade {ClassUpdate.INTRASELL_MYSQL_BINARIES} nach {mySqlZIP}"
            WriteLog(logMsg)
            achtung.ShowMessage("Datenbank", logMsg)
            ClassUpdate.DownloadFile(ClassUpdate.INTRASELL_MYSQL_BINARIES, mySqlZIP)
        Else
            Dim logMsg = String.Format("File wurde bereits heruntergeladen {0}", mySqlZIP)
            achtung.ShowMessage("Datenbank", logMsg)
            WriteLog(logMsg)
        End If

        achtung.ShowMessage("Datenbank", "Dateien entzippen ...")
        If Not silent Then
            If MsgBox(Messages.Setup_MySQL_moechten_installieren, vbYesNo) = vbYes Then
                ExtractZipFile(mySqlZIP, Nothing, SETUP_DRIVE)
            End If
        Else
            ExtractZipFile(mySqlZIP, Nothing, SETUP_DRIVE)
        End If


        'Start MySQL Process 
        achtung.ShowMessage("Datenbank", "Starte Datenbankserver ...")
        Shell(MYSQL_PROCESS_NAME, AppWinStyle.Hide, Wait:=True, Timeout:=5000)
        'Check if Connection is possible 

        Dim cnt = 0
        Try
            Dim dbErreichbar = FirstRow("select count(User) From mysql.user")
            While Not IsNumeric(dbErreichbar) AndAlso cnt < 10
                Thread.Sleep(1000)
                cnt += 1
            End While
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try


        'INSTALL Tables 
        achtung.ShowMessage("Datenbank", "Installiere IntraSell Datenbank ...")
        cnt = 0
        Shell(MYSQL_INTRASELL_BATCH_INSTALL, AppWinStyle.Hide, Wait:=True, Timeout:=5000)
        Try
            Dim tabellenAngelegt = FirstRow("select count(Id) From upgradelog")
            While Not IsNumeric(tabellenAngelegt) AndAlso cnt < 10
                Thread.Sleep(1000)
                cnt += 1
            End While
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try

        WriteLog("Check db connection ...")
        Try
            Dim gotConnection As Boolean = VarValue_Default("ADMIN", "WebShop") = "WebShop"
            If gotConnection Then
                SetUpMySqlServer = True
                WriteLog("Setup MySQL OK")
                If Not silent Then
                    UserMessagePopUp("Datenbank", Messages.ModuleSetup_MySQL_OK, MsgBoxStyle.OkOnly)
                End If
            End If
        Catch ex As Exception
            SetUpMySqlServer = False
            WriteLog("Setup MySQL FAILED. Fehler: " + ex.Message)
            If Not silent Then
                UserMessagePopUp("Datenbank", Messages.Setup_MySQL_Failed, vbCritical)
            End If
        End Try
        'DONE
        WriteLog("Setup MySQL DONE")
    End Function

    'Vorlagen Kopieren weil bei einem Update mit Publischer Vorlagen wieder auf alte Vorlagen einstellet wird 
    Public Sub CopyVorlagenUndConfig()
        Dim INSTALL_VORLAGEN = "Vorlagen"

        If Not Directory.Exists(VORLAGEN_FOLDER) Then 'Einmal sichern
            Directory.CreateDirectory(VORLAGEN_FOLDER)
            Shell("xcopy " & INSTALL_VORLAGEN & " " & VORLAGEN_FOLDER & "  /S/C/H/Y", AppWinStyle.Hide, True, 5)
            'Konfiguration einmalig kopieren, falls neue eingestellt !!!
            'Shell("xcopy *.config " & INTRASELL_FOLDER & " /D", AppWinStyle.Hide, True, 5)
        End If
        'wieder nach intrasell kopieren /falls neue installation und der user braucht alte vorlagen
        Shell("xcopy " & VORLAGEN_FOLDER & " " & INSTALL_VORLAGEN & "  /S/C/H/Y", AppWinStyle.Hide, True, 5)
        'Shell("xcopy " & INTRASELL_FOLDER & "\*.config /Y", AppWinStyle.Hide, True, 5)
    End Sub

    Public Sub BackupConfig()
        Shell("xcopy *.config " & INTRASELL_FOLDER & " /Y", AppWinStyle.Hide, True, 5)
    End Sub

    ''' <summary>
    ''' Lade Konfiguration (connection String)
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub LoadConfig()
        Dim settings = New ClassSettings()
        If IsNull(settings.Read("intrasell_daten_2_ConnectionString")) Then
            'Settings für PLUGINS müssen existieren 
            Dim defaultConnString = My.Settings.intrasell_daten_2_ConnectionString

            If Not Directory.Exists(INTRASELL_FOLDER) Then
                Directory.CreateDirectory(INTRASELL_FOLDER)
            End If

            settings.Write("intrasell_daten_2_ConnectionString", defaultConnString)
        Else
            Dim cTest = settings.Read("intrasell_daten_2_ConnectionString")
            AppConfigFileSettings.UpdateAppSettings("IntraSell_Net.My.MySettings.intrasell_daten_2_ConnectionString", cTest)
            My.Settings.Reload()
            Try
                My.Settings.intrasell_daten_2_ConnectionString = cTest
            Catch ex As Exception
                HandleAppError(ex, Silent:=True)
            End Try
        End If
    End Sub

    Public Sub SpracheFestlegen(neueSprache As String, Optional updateSettings As Boolean = True)
        Try
            If updateSettings Then
                SetVarValue("LANGUAGE", neueSprache)
            End If
            ' Visual Basic
            ' Sets the UI culture to French (France)
            If neueSprache = "BUL" Then
                Thread.CurrentThread.CurrentUICulture = New CultureInfo("bg")
            ElseIf neueSprache = "ENG" Then
                Thread.CurrentThread.CurrentUICulture = New CultureInfo("en")
            ElseIf neueSprache = "ARA" Then
                Thread.CurrentThread.CurrentUICulture = New CultureInfo("ar")
            ElseIf neueSprache = "TUR" Then
                Thread.CurrentThread.CurrentUICulture = New CultureInfo("tr")
            ElseIf neueSprache = "THAI" Then
                Thread.CurrentThread.CurrentUICulture = New CultureInfo("th")
            ElseIf neueSprache = "ROM" Then
                Thread.CurrentThread.CurrentUICulture = New CultureInfo("ro")
            ElseIf neueSprache = "ZH" Then
                Thread.CurrentThread.CurrentUICulture = New CultureInfo("zh")
            Else
                Thread.CurrentThread.CurrentUICulture = New CultureInfo("de")
            End If

            My.Settings.language = neueSprache
            My.Settings.Save()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub
End Module
