Imports System.Configuration
Imports System.Text.RegularExpressions

Public Class FormSetting

	Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

    Private Sub TB_OpcuaAddress_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TB_OpcuaAddress.KeyPress
        Dim tb As TextBox = CType(sender, TextBox)

        ' Permetti solo numeri, punto e backspace
        If Not Char.IsDigit(e.KeyChar) AndAlso e.KeyChar <> "."c AndAlso e.KeyChar <> ChrW(Keys.Back) Then
            e.Handled = True
            Return
        End If

        ' Simula il testo risultante dopo la pressione del tasto
        Dim proposedText As String
        If e.KeyChar = ChrW(Keys.Back) Then
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
            ElseIf tb.SelectionStart > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart - 1, 1)
            Else
                proposedText = tb.Text
            End If
        Else
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
                proposedText = proposedText.Insert(tb.SelectionStart, e.KeyChar)
            Else
                proposedText = tb.Text.Insert(tb.SelectionStart, e.KeyChar)
            End If
        End If

        ' Controlla ciascun ottetto
        Dim parts() As String = proposedText.Split("."c)
        For Each part As String In parts
            If part.Length > 3 Then
                e.Handled = True
                Return
            End If
            If part.Length > 0 Then
                Dim num As Integer
                If Integer.TryParse(part, num) AndAlso num > 255 Then
                    e.Handled = True
                    Return
                End If
            End If
        Next

        ' Se l’utente preme Enter, valida IP completo
        If e.KeyChar = ChrW(Keys.Enter) Then
            Dim isValid As Boolean = parts.Length = 4 AndAlso parts.All(Function(p) Integer.TryParse(p, 0) AndAlso CInt(p) <= 255)
            If Not isValid Then
                MessageBox.Show("L'indirizzo IP inserito non è valido! Inserisci un IPv4 corretto.")
                tb.Text = ""
                tb.Focus()
            End If
            e.Handled = True
        End If
    End Sub


    Private Sub TB_OpcuaPort_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TB_OpcuaPort.KeyPress
        Dim tb As TextBox = CType(sender, TextBox)

        ' Consenti solo numeri e backspace
        If Not Char.IsDigit(e.KeyChar) AndAlso e.KeyChar <> ChrW(Keys.Back) Then
            e.Handled = True
            Return
        End If

        Dim proposedText As String

        ' Simula il testo risultante dopo la pressione del tasto
        If e.KeyChar = ChrW(Keys.Back) Then
            ' Gestione backspace
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
            ElseIf tb.SelectionStart > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart - 1, 1)
            Else
                proposedText = tb.Text
            End If
        Else
            ' Inserimento di un carattere numerico
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
                proposedText = proposedText.Insert(tb.SelectionStart, e.KeyChar)
            Else
                proposedText = tb.Text.Insert(tb.SelectionStart, e.KeyChar)
            End If
        End If

        ' Controlla che il testo non superi 5 cifre
        If proposedText.Length > 5 Then
            e.Handled = True
            Return
        End If

        ' Se il testo non è vuoto, verifica che il numero sia <= 65535
        If proposedText.Length > 0 Then
            Dim num As Integer
            If Not Integer.TryParse(proposedText, num) OrElse num > 65535 Then
                e.Handled = True
                Return
            End If
        End If
    End Sub


    Private Sub TB_Selfdischarge_Rate_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TB_Selfdischarge_Rate.KeyPress
        Dim tb As TextBox = CType(sender, TextBox)

        ' Consenti solo numeri, backspace e virgola/punto
        If Not Char.IsDigit(e.KeyChar) AndAlso e.KeyChar <> ChrW(Keys.Back) AndAlso e.KeyChar <> ","c AndAlso e.KeyChar <> "."c Then
            e.Handled = True
            Return
        End If

        ' Normalizza: sostituisci eventuale virgola con punto
        If e.KeyChar = ","c Then
            e.KeyChar = "."c
        End If

        ' Permetti un solo punto
        If e.KeyChar = "."c AndAlso tb.Text.Contains("."c) Then
            e.Handled = True
            Return
        End If

        ' Simula il testo risultante dopo la pressione del tasto
        Dim proposedText As String
        If e.KeyChar = ChrW(Keys.Back) Then
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
            ElseIf tb.SelectionStart > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart - 1, 1)
            Else
                proposedText = tb.Text
            End If
        Else
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
                proposedText = proposedText.Insert(tb.SelectionStart, e.KeyChar)
            Else
                proposedText = tb.Text.Insert(tb.SelectionStart, e.KeyChar)
            End If
        End If

        ' Controllo massimo 4 cifre prima del punto e massimo 6 cifre dopo il punto
        If proposedText.Contains("."c) Then
            Dim parts() As String = proposedText.Split("."c)
            ' Prima del punto
            If parts(0).Length > 4 Then
                e.Handled = True
                Return
            End If
            ' Dopo il punto
            If parts.Length > 1 AndAlso parts(1).Length > 6 Then
                e.Handled = True
                Return
            End If
        Else
            ' Se non c'è punto, controlla solo le cifre totali prima del punto
            If proposedText.Length > 4 Then
                e.Handled = True
                Return
            End If
        End If
    End Sub


    Private Sub TB_LocalDbRows_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TB_LocalDbRows.KeyPress
        Dim tb As TextBox = CType(sender, TextBox)

        ' Consenti solo numeri e backspace
        If Not Char.IsDigit(e.KeyChar) AndAlso e.KeyChar <> ChrW(Keys.Back) Then
            e.Handled = True
            Return
        End If

        ' Simula il testo risultante dopo la pressione del tasto
        Dim proposedText As String

        If e.KeyChar = ChrW(Keys.Back) Then
            ' Gestione backspace
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
            ElseIf tb.SelectionStart > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart - 1, 1)
            Else
                proposedText = tb.Text
            End If
        Else
            ' Inserimento di un carattere numerico
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
                proposedText = proposedText.Insert(tb.SelectionStart, e.KeyChar)
            Else
                proposedText = tb.Text.Insert(tb.SelectionStart, e.KeyChar)
            End If
        End If

        ' Controllo lunghezza max 4
        If proposedText.Length > 4 Then
            e.Handled = True
            Return
        End If

        ' Controllo valore numerico <= 65535
        If proposedText.Length > 0 Then
            Dim num As Integer
            If Not Integer.TryParse(proposedText, num) OrElse num > 65535 Then
                e.Handled = True
                Return
            End If
        End If
    End Sub


    Private Sub TB_LocalDbFreq_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TB_LocalDbFreq.KeyPress
        Dim tb As TextBox = CType(sender, TextBox)

        ' Consenti solo numeri e backspace
        If Not Char.IsDigit(e.KeyChar) AndAlso e.KeyChar <> ChrW(Keys.Back) Then
            e.Handled = True
            Return
        End If

        ' Simula il testo risultante dopo la pressione del tasto
        Dim proposedText As String

        If e.KeyChar = ChrW(Keys.Back) Then
            ' Gestione backspace
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
            ElseIf tb.SelectionStart > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart - 1, 1)
            Else
                proposedText = tb.Text
            End If
        Else
            ' Inserimento di un carattere numerico
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
                proposedText = proposedText.Insert(tb.SelectionStart, e.KeyChar)
            Else
                proposedText = tb.Text.Insert(tb.SelectionStart, e.KeyChar)
            End If
        End If

        ' Controllo lunghezza max 4
        If proposedText.Length > 4 Then
            e.Handled = True
            Return
        End If

        ' Controllo valore numerico <= 65535
        If proposedText.Length > 0 Then
            Dim num As Integer
            If Not Integer.TryParse(proposedText, num) OrElse num > 65535 Then
                e.Handled = True
                Return
            End If
        End If
    End Sub


    Private Sub TB_LocalDbFifoDays_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TB_LocalDbFifoDays.KeyPress
        Dim tb As TextBox = CType(sender, TextBox)

        ' Consenti solo numeri e backspace
        If Not Char.IsDigit(e.KeyChar) AndAlso e.KeyChar <> ChrW(Keys.Back) Then
            e.Handled = True
            Return
        End If

        ' Simula il testo risultante dopo la pressione del tasto
        Dim proposedText As String

        If e.KeyChar = ChrW(Keys.Back) Then
            ' Gestione backspace
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
            ElseIf tb.SelectionStart > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart - 1, 1)
            Else
                proposedText = tb.Text
            End If
        Else
            ' Inserimento di un carattere numerico
            If tb.SelectionLength > 0 Then
                proposedText = tb.Text.Remove(tb.SelectionStart, tb.SelectionLength)
                proposedText = proposedText.Insert(tb.SelectionStart, e.KeyChar)
            Else
                proposedText = tb.Text.Insert(tb.SelectionStart, e.KeyChar)
            End If
        End If

        ' Controllo lunghezza max 4
        If proposedText.Length > 4 Then
            e.Handled = True
            Return
        End If

        ' Controllo valore numerico <= 65535
        If proposedText.Length > 0 Then
            Dim num As Integer
            If Not Integer.TryParse(proposedText, num) OrElse num > 65535 Then
                e.Handled = True
                Return
            End If
        End If
    End Sub



    Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles ButtonSave.Click

        If TB_OpcuaAddress.Text = "" Then
            MsgBox("The IP field is empty, please correct and try again")
            Exit Sub
        End If

        If TB_OpcuaPort.Text = "" Then
            MsgBox("The PORT field is empty, please correct and try again")
            Exit Sub
        End If

        If TB_Selfdischarge_Rate.Text = "" Then
            MsgBox("The Self-Discharge Rate field is empty, please correct and try again")
            Exit Sub
        End If

        If TB_LocalDbFreq.Text = "" Then
            MsgBox("The Update Frequency field is empty, please correct and try again")
            Exit Sub
        End If

        If TB_LocalDbRows.Text = "" Then
            MsgBox("The Number of Rows field is empty, please correct and try again")
            Exit Sub
        End If

        If TB_LocalDbFifoDays.Text = "" Then
            MsgBox("The Number of Fifo Days field is empty, please correct and try again")
            Exit Sub
        End If

        config.AppSettings.Settings("OPCUA_IP").Value = TB_OpcuaAddress.Text
        config.AppSettings.Settings("OPCUA_PORT").Value = TB_OpcuaPort.Text
        config.AppSettings.Settings("SELF_DISCHARGE_RATE").Value = TB_Selfdischarge_Rate.Text
        config.AppSettings.Settings("FREQ_DB_INSERT_SEC").Value = TB_LocalDbFreq.Text
        config.AppSettings.Settings("FREQ_DB_INSERT_N_ROW").Value = TB_LocalDbRows.Text
        config.AppSettings.Settings("FIFO_LOCAL_DB_GG").Value = TB_LocalDbFifoDays.Text
        config.AppSettings.Settings("LOG_REC").Value = ChBx_DataLogging.Checked.ToString()


        config.Save(ConfigurationSaveMode.Modified)
        ConfigurationManager.RefreshSection("appSettings")

        Select Case MsgBox("Configuration Saved, Restart the Application?", MsgBoxStyle.YesNoCancel, "Restart")
            Case MsgBoxResult.Yes
                Application.Restart()
            Case MsgBoxResult.No
                Me.Close()
        End Select

    End Sub

    Private Sub FormSetting_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim AppSettings = ConfigurationManager.AppSettings

        TB_OpcuaAddress.Text = AppSettings("OPCUA_IP")
        TB_OpcuaPort.Text = AppSettings("OPCUA_PORT")
        TB_Selfdischarge_Rate.Text = AppSettings("SELF_DISCHARGE_RATE")
        TB_LocalDbFreq.Text = AppSettings("FREQ_DB_INSERT_SEC")
        TB_LocalDbRows.Text = AppSettings("FREQ_DB_INSERT_N_ROW")
        TB_LocalDbFifoDays.Text = AppSettings("FIFO_LOCAL_DB_GG")
        ChBx_DataLogging.Checked = CBool(AppSettings("LOG_REC"))

    End Sub
End Class