Option Strict On
Option Explicit On
Imports System.IO
Imports IntraSell_DLL
Imports IntraSell_Net_Base

''' <summary>
''' 
''' </summary>
''' <remarks></remarks>
Public Module ModuleLogIn

    Public Const BLUE_TOKEN_LENGTH = 10
    Private LAST_USER_SETTINGS As String = "IntraSell_user_" & Environment.MachineName & ".tmp"


    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub SaveLastUsername()
        Try
            WriteLog("Set last username: " & Username)
            Using outfile As New StreamWriter(LAST_USER_SETTINGS, False)
                outfile.WriteLine(Username)
            End Using
        Catch ex As Exception
            WriteLog("Cannot set last username! Fehler: " & ex.Message)
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub ReadLastUsername()
        Try
            'WriteLog("Get last username")
            Using infile As New StreamReader(LAST_USER_SETTINGS, True)
                Username = infile.ReadLine()
            End Using
        Catch ex As Exception
            WriteLog("Cannot get last username! Fehler: " & ex.Message)
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="username"></param>
    ''' <param name="passwort"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function CanLogin(username As String, passwort As String) As Boolean
        Dim sql As String
        sql = "select IDNR from ofMitarbeiter where Username = @Username and (Passwort = @Passwort or Passwort is Null) order by IDNR desc"
        Dim cmd = New MySql.Data.MySqlClient.MySqlCommand(sql)
        cmd.Parameters.AddWithValue("Username", username)
        cmd.Parameters.AddWithValue("Passwort", passwort)

        Dim idnr = FirstRow(cmd)
        If IsNumeric(idnr) Then
            MitarbeiterID = CInt(idnr)
            Return True
        End If
        Return False
    End Function

    Public Function LoginUser(username As String, passwort As String) As Boolean
        Try
            'check if mitarbeiter login ok
            WriteLog("Login user " & username)

            Dim sql As String
            sql = "select IDNR from ofMitarbeiter where Username=@Username and (Passwort=@Passwort or Passwort is Null) order by idnr desc"
            Dim cmd = New MySql.Data.MySqlClient.MySqlCommand(sql)
            cmd.Parameters.AddWithValue("Username", username)
            cmd.Parameters.AddWithValue("Passwort", passwort)
            Dim IDNR = FirstRow(cmd)
            If IsNumeric(IDNR) Then
                MitarbeiterID = CInt(IDNR)
                LastLogin = Now

                Call SaveLastUsername()
                'Die Einstellung für den User setzen falls noch nicht passiert
                VarValue_Default("LANGUAGE_DOK_" & MitarbeiterID, "DEU")
                Return True
                Exit Function
            End If
            Return False
            WriteLog("Login nicht erfolgreich für User " + username)
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
            Return False
        End Try
    End Function


    Public Function LoginUserMitToken(token As String) As Boolean
        Try
            'check if mitarbeiter login ok
            WriteLog("Check token " & token)
            If token.Length >= BLUE_TOKEN_LENGTH Then
                Dim sql As String
                sql = "select IDNR from ofMitarbeiter where (Passwort = @token )"
                Dim cmd = New MySql.Data.MySqlClient.MySqlCommand(sql)
                cmd.Parameters.AddWithValue("token", token)
                Dim IDNR = FirstRow(cmd)
                If IsNumeric(IDNR) Then
                    MitarbeiterID = CInt(IDNR)
                    LastLogin = Now
                    'Die Einstellung für den User setzen falls noch nicht passiert
                    VarValue_Default("LANGUAGE_DOK_" & MitarbeiterID, "DEU")
                    Return True
                    Exit Function
                End If

                'else admin login
                Return False
                WriteLog("Login nicht erfolgreich für User mit token " & token)
            End If

        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
            Return False
        End Try
        Return False
    End Function

    Function NeedsLogin() As Boolean
        'hide login window if no user in db with pwd  
        Dim rsTable = OpenRecordsetInMemory("select distinct passwort p from ofMitarbeiter where passwort is not null and passwort!=''")
        If rsTable.Rows.Count > 0 Then
            Dim rs = rsTable.Rows(0)
            If IsDBNull(rs("p")) Then
                WriteLog("Weiter ohne Anmedlung ...")
                Return False
            End If
        Else
            WriteLog("Weiter ohne Anmedlung ...")
            Return False
        End If

        Return True
    End Function

End Module
