Imports System.ComponentModel

Public Class frmMass_Change
    Dim SQL As String
    Dim _CONTROLID As Integer
    Private Sub frmMass_Change_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            SUCCESSFULL = False
            Dim msg = "Anzahl zu ändernde Datensätze: "
            If USER_LANGUAGE <> "de-DE" Then
                msg = "Count of records to be changed: "
            End If
            lblCount.Text = msg & MASS_RECORD_IDs2CHANGE.Count
            cmbColumn.Items.Clear()
            For Each Str As String In MASS_COLUMN_LIST
                If Str.ToLower = "addedwho" Or Str.ToLower = "changedwho" Or Str.ToLower = "addedwhen" Or Str.ToLower = "changedwhen" Then
                    Continue For
                Else
                    cmbColumn.Items.Add(Str)
                End If
            Next
            txtNewValue.Text = ""
            Me.cmbColumn.SelectedIndex = -1
        Catch ex As Exception
            MsgBox("Unexpected Error in load form:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Private Sub btncancel_Click(sender As Object, e As EventArgs) Handles btncancel.Click
        Me.Close()
    End Sub
    Private Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
        Try
            _CONTROLID = 0
            If txtNewValue.Text <> "" And Me.cmbColumn.SelectedIndex <> -1 Then
                Dim msg = "Sind Sie sicher, dass Sie diese Massenänderung durchführen wollen?" & vbNewLine & MASS_RECORD_IDs2CHANGE.Count.ToString & " Datensätze werden geändert!"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "Are You sure You want to execute this mass change?" & vbNewLine & MASS_RECORD_IDs2CHANGE.Count.ToString & " records will be changed!"
                End If

                Dim result As MsgBoxResult
                result = MessageBox.Show(msg, CAPTION_CONFIRMATION, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                If result = MsgBoxResult.Yes Then
                    Cursor = Cursors.WaitCursor
                    LOGGER.Info(String.Format("### Starting MassChange of column '{0}' with value '{1}'....###", cmbColumn.Text, txtNewValue.Text))
                    ClassHelper.InsertEssential_Log(USER_GUID, "User-ID", String.Format("### Starting MassChange of column '{0}' with value '{1}'....###", cmbColumn.Text, txtNewValue.Text))
                    Me.Cursor = Cursors.WaitCursor
                    SQL = String.Format("SELECT GUID FROM TBPMO_CONTROL WHERE COL_NAME = '{0}' AND FORM_ID = {1}", cmbColumn.Text, CURRENT_ENTITY_ID)
                    Dim control_Id = MYDB_ECM.GetScalarValue(SQL)

                    If Not IsNothing(control_Id) Then
                        _CONTROLID = control_Id
                    End If
                    ProgressBar1.Visible = True
                    lblStateBW.Text = "Preparing BackgroundWorker..."
                    lblStateBW.Visible = True
                    ProgressBar1.Maximum = MASS_RECORD_IDs2CHANGE.Count
                    AddHandler BackgroundWorker.DoWork, AddressOf bwDowork
                    '.. und starten
                    BackgroundWorker.RunWorkerAsync()
                End If
            Else
                MessageBox.Show("Please choose an entry from dropdown and input a new value.")
            End If

        Catch ex As Exception
            MsgBox("Unexpected Error in Execute mass change:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
        Cursor = Cursors.Default
    End Sub
    Dim _Error = False
    Sub bwDowork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        Dim val = txtNewValue.Text


        If _CONTROLID <> 0 Then
            SQL = String.Format("SELECT CONTROL_TYPE_ID FROM TBPMO_CONTROL WHERE GUID = {0}", _CONTROLID)
            Dim control_type_ID = MYDB_ECM.GetScalarValue(SQL)
            If control_type_ID = 4 Then
                    Try
                        val = CDate(val)
                    Catch ex As Exception
                        MsgBox("Error in Converting value '" & val & "' to date", MsgBoxStyle.Critical)
                        Cursor = Cursors.Default
                        Exit Sub
                    End Try
                End If
                If control_type_ID = 7 Or control_type_ID = 12 Or control_type_ID = 14 Then
                    stateBW = "Deleting the old values..."
                    'Dim msg As String
                    'msg = "Achtung: für diese Spalte existieren mehrere Werte. Diese Werte werden gelöscht." & vbNewLine & "Wollen Sie dennoch fortfahren?"
                    'If USER_LANGUAGE <> "de-DE" Then
                    '    msg = "Attention: there are multiple values for this column. These values will be deleted." & vbNewLine & "Would You like to continue?"
                    'End If
                    'Dim result1 As MsgBoxResult
                    'result1 = MessageBox.Show(msg, CAPTION_CONFIRMATION, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    For Each Record As String In MASS_RECORD_IDs2CHANGE
                    Dim del = String.Format("DELETE FROM TBPMO_CONTROL_VALUE WHERE CONTROL_ID = {0} AND RECORD_ID = {1}", _CONTROLID, CInt(Record))
                    MYDB_ECM.ExecuteNonQuery(del)
                    ClassProxy.PRPROXY_CONTROL_DEL(CInt(Record), CURRENT_ENTITY_ID, _CONTROLID)
                Next
                End If
                Try
                    Dim RIGHT_ONLY_READ_RECORD_FILE = False
                    Dim i As Integer = 1
                    For Each Record As String In MASS_RECORD_IDs2CHANGE
                        stateBW = String.Format("Working on record {0} of {1}...", i, MASS_RECORD_IDs2CHANGE.Count.ToString)
                        If SQL_RECORD_AND_FILE_READ_ONLY <> "" Then
                            RIGHT_ONLY_READ_RECORD_FILE = ClassHelper.Check_Record_Read_only(CInt(Record), CURRENT_ENTITY_ID)
                        End If
                        If RIGHT_ONLY_READ_RECORD_FILE = False Then
                        SQL = String.Format("SELECT GUID FROM TBPMO_CONTROL_VALUE WHERE CONTROL_ID = {0} AND RECORD_ID = {1}", _CONTROLID, CInt(Record))
                        Dim ex_GUID = MYDB_ECM.GetScalarValue(SQL)
                        If Not IsNothing(ex_GUID) Then
                                SQL = String.Format("UPDATE TBPMO_CONTROL_VALUE SET VALUE = '{0}',CHANGED_WHO = '{1}' WHERE GUID = {2}", val, USER_USERNAME, ex_GUID)
                            If MYDB_ECM.ExecuteNonQuery(SQL) = False Then
                                _Error = True
                                LOGGER.Warn("Error in updating the value for Record: " & Record)

                            Else
                                ClassProxy.PRPROXY_CONTROL_VALUE_UPD_INS(CURRENT_ENTITY_ID, _CONTROLID, CInt(Record), val)
                            End If
                            Else
                            SQL = String.Format("INSERT INTO TBPMO_CONTROL_VALUE (CONTROL_ID, RECORD_ID, VALUE, ADDED_WHO) VALUES ({0},{1},'{2}','{3}')", _CONTROLID, CInt(Record), val, USER_USERNAME)
                            If MYDB_ECM.ExecuteNonQuery(SQL) = False Then
                                _Error = True
                                LOGGER.Warn("Error in inserting the value for Record: " & Record)
                            Else
                                ClassProxy.PRPROXY_CONTROL_VALUE_UPD_INS(CURRENT_ENTITY_ID, _CONTROLID, CInt(Record), val)
                            End If
                            End If
                        End If
                        BackgroundWorker.ReportProgress(i)
                        i += 1
                    Next
                    SUCCESSFULL = True
                LOGGER.Info(String.Format("### MassChange finished successfully! ###"))
            Catch ex As Exception
                LOGGER.Warn("Unexpected Error in Getting record to be changed:" & ex.Message)
                _Error = True
                End Try
            Else
            LOGGER.Warn("No defined Control found!")
            _Error = True
        End If

    End Sub
    Dim stateBW As String
    Private Sub BackgroundWorker_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker.ProgressChanged
        Me.ProgressBar1.Value = e.ProgressPercentage
        lblStateBW.Text = stateBW
    End Sub

    Private Sub BackgroundWorker_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker.RunWorkerCompleted
        Me.ProgressBar1.Visible = False
        Me.lblStateBW.Visible = False
        Dim msg As String
        msg = "Alle Änderungen wurden ausgeführt!"

        If USER_LANGUAGE <> "de-DE" Then
            msg = "All changes were executed!"
        End If
        If _Error = True Then
            LOGGER.Warn(String.Format("### MassChange finished - WITH errors!! ###"))
            If USER_LANGUAGE <> "de-DE" Then
                msg = msg & vbNewLine & "But errors occured while updating values! Check the log"
            Else
                msg = msg & vbNewLine & "Aber während des Update-Vorgangs erreigneten sich Fehler! Prüfen Sie die Logdatei!"
            End If

        End If
        MsgBox(msg, MsgBoxStyle.Information)
        Me.Cursor = Cursors.Default
    End Sub
End Class