Imports IntraSell_DLL
Imports MySql.Data.MySqlClient

Public Class VorgangDruck

    Const VAR_AUTOMATISCH_ABSCHLIESSEN As String = "AUTOMATISCH_ABSCHLIESSEN"
    Dim loading As Boolean = True

    Private _VorgangTyp, _VorgangNummer As String, _KundenNr As Integer

    Private Sub OK_Button_Click(sender As Object, e As System.EventArgs) Handles OK_Button.Click
        Try

            Dim Viewer As String = "WORD"
            If WORD_RadioButton.Checked Then Viewer = "WORD"
            If PDF_RadioButton.Checked Then Viewer = "PDF"
            If EMAIL_RadioButton.Checked Then Viewer = "OUTLOOK"
            If EMAILATTACHMENT_RadioButton.Checked Then Viewer = "OUTLOOK"
            If XML_RadioButton.Checked Then Viewer = "XML"
            If HTML_RadioButton.Checked Then Viewer = "HTML"
            MergeVorlage(Viewer)
            DialogResult = DialogResult.OK
            Close()

        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub Cancel_Button_Click(sender As Object, e As System.EventArgs) Handles Cancel_Button.Click
        Try
            DialogResult = DialogResult.Cancel
            Close()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub VorgangKonvertieren_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
        Try
            loading = True
            FillComboBox(TypComboBox, "SELECT '' as Typ, '' as Bezeichnung union SELECT Typ, Bezeichnung FROM buchVorgangTyp ORDER By Bezeichnung", "Bezeichnung", "Typ")

            TypComboBox.SelectedValue = _VorgangTyp
            NummerTextBox.Text = _VorgangNummer
            KundNrAdressenControl.IDNR = _KundenNr
            loading = False
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub


    Sub Init(VorgangTyp As String, VorgangNummer As String, KundenNr As String)
        _VorgangTyp = VorgangTyp
        _VorgangNummer = VorgangNummer
        _KundenNr = KundenNr

        FillComboBox(VorlageListBox,
             " SELECT concat(a.Dateiname, ' ', a.Engine) as Dateiname, a.ID FROM buchVorgaengeAusdrucke a LEFT JOIN buchVorgaengeAusdruckeLog l ON a.Dateiname = l.Dateiname " &
             " GROUP BY a.Dateiname, a.ID, a.Bereich " &
             " HAVING a.Bereich = 'VORGANG_" & _VorgangTyp & "'" &
             " ORDER BY Count(a.ID) DESC , a.Dateiname;", "Dateiname", "Id")
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            Dim Dateiname As String = VorlageListBox.SelectedItem("Dateiname")
            Dim VorlageId As String = VorlageListBox.SelectedValue

            Dim ve As New VorlageEditor(Dateiname) With {
                .MdiParent = MdiParent
            }
            ve.Show()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub bntVorlagen_Click(sender As Object, e As EventArgs) Handles bntVorlagen.Click
        VorgangEinstellungen.ShowDialog()
    End Sub

    Private Sub btnVorlageWählen_Click(sender As Object, e As EventArgs) Handles btnVorlageWählen.Click
        Try
            Dim fileOpen = New OpenFileDialog
            fileOpen.ShowDialog()
            If IO.File.Exists(fileOpen.FileName) Then
                Dim engine As String = "RTF"

                If fileOpen.FileName.Contains(".dot") Then
                    engine = "XML"
                End If

                Dim sql As String = "Insert into buchvorgaengeausdrucke (Dateiname, Engine, Bereich) values (@Dateiname, @Engine, @Bereich)"
                Dim cmd = New MySqlCommand(sql)
                cmd.Parameters.AddWithValue("Dateiname", fileOpen.FileName)
                cmd.Parameters.AddWithValue("Engine", engine)
                cmd.Parameters.AddWithValue("Bereich", "VORGANG_" & _VorgangTyp)
                RunSQL(cmd)
                Init(_VorgangTyp, _VorgangNummer, _KundenNr)
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub SofortSenden_CheckBox_Click(sender As Object, e As EventArgs) Handles SofortSenden_CheckBox.Click
        Try
            Dim mail = KundenEmailVorbereiten(_VorgangTyp, _VorgangNummer)
            Try
                mail.Mailtext = FirstRow("Select EmailText from buchvorgaengeausdrucke where ID=" & Me.VorlageListBox.SelectedValue)
            Catch ex As Exception
            End Try

            If String.IsNullOrEmpty(Me.txtEmail.Text) Then
                Me.txtEmail.Text = mail.EmailTo
                Me.txtMailBetreff.Text = mail.Subject
                Me.txtMailtext.Text = mail.Mailtext
            End If
            Me.PanelEmail.Visible = SofortSenden_CheckBox.Checked
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub SofortSenden_CheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles SofortSenden_CheckBox.CheckedChanged

    End Sub



    'Option Compare Database
    'Option Explicit

    'Private Sub brnNeueVorlagen_Click()
    '    MsgBox("Bitte wenn Sie die Vorlagennamen ändern oder neue Vorlagen einfügen, stellen Sie sicher dass die entsprechende Vorlagen Dateien auch existieren!")
    '    DoCmd.OpenTable("buchVorgaengeAusdrucke")
    'End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="Viewer">WORD, OUTLOOK, HTML</param>
    ''' <remarks></remarks>
    Sub MergeVorlage(Viewer As String)
        WriteLog("MergeVorlage start. Viewer " + Viewer)
        Try
            Application.UseWaitCursor = True
            'Dim Dateiname As String = VorlageListBox.SelectedItem("Dateiname")
            Dim VorlageId As String = VorlageListBox.SelectedValue
            Dim Dateiname As String = FirstRow("select Dateiname from buchVorgaengeAusdrucke where Id = " & VorlageId)
            Dim Engine As String = FirstRow("select engine from buchVorgaengeAusdrucke where Id = " & VorlageId)

            Dim Nummer = NummerTextBox.Text
            Dim VorgangTyp = TypComboBox.SelectedValue
            Dim resultFile = Nothing

            If IsNull(Dateiname) Or Dateiname = "" Then
                MsgBox("Wählen Sie bitte eine Vorlage aus!", vbCritical)
                Exit Sub
            Else

                If UCase(Engine).Contains("XML") Then
                    resultFile = OpenAusdruck_inWord_XML(VorgangTyp, Nummer, Dateiname, Viewer, Silent:=False)
                End If

                If UCase(Engine).Contains("RTF") And Viewer = "HTML" Then
                    resultFile = OpenAusdruck_InWord_Filename_RTF(VorgangTyp, Nummer, Dateiname, Silent:=True)
                End If

                'not supported 
                If UCase(Engine).Contains("RTF") And Viewer <> "HTML" Then
                    resultFile = OpenAusdruck_InWord_Filename_RTF(VorgangTyp, Nummer, Dateiname, Silent:=False)
                End If

                'not supported 
                If UCase(Engine).Contains("WORD") Then
                    resultFile = OpenAusdruck_inWord_Filename(VorgangTyp, Nummer, Dateiname)
                End If

                Senden(resultFile)

                WriteLog(Dateiname)
            End If
        Catch ex As Exception
            Application.UseWaitCursor = False
            HandleAppError(ex)
        Finally
            Application.UseWaitCursor = False
        End Try
    End Sub

    Private Sub btnMailTextSpeichern_Click(sender As Object, e As EventArgs) Handles btnMailTextSpeichern.Click
        Try
            Try
                RunSQL("alter table buchvorgaengeausdrucke add EmailText TEXT")
            Catch ex As Exception
            End Try

            Dim cmd As New MySqlCommand("Update buchvorgaengeausdrucke set EmailText = @EmailText where Id=@Id")
            cmd.Parameters.AddWithValue("EmailText", Me.txtMailtext.Text)
            cmd.Parameters.AddWithValue("Id", Me.VorlageListBox.SelectedValue)
            RunSQL(cmd)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Sub Senden(resultfile As String)
        If SofortSenden_CheckBox.Checked Then
            Dim Nummer = NummerTextBox.Text
            Dim VorgangTyp = TypComboBox.SelectedValue
            Dim mail = KundenEmailVorbereiten(VorgangTyp, Nummer)
            mail.SofortSenden = True
            mail.EmailTo = Me.txtEmail.Text
            mail.Subject = Me.txtMailBetreff.Text
            mail.Mailtext = Me.txtMailtext.Text
            mail.FilePath = resultfile
            DokumentOeffnen(MAIL_GRITON, resultfile, mail)
        Else
            Process.Start("file://" & resultfile)
        End If
    End Sub


    'Private Sub btnEmailAttachment_Click()
    '    'XML Engine Vorgänge können nur als Attachment geschickt werden
    '    mergeVorlage("OUTLOOK")
    'End Sub


    'Private Sub btnEmail_Click()
    '    Dim Dateiname : Dateiname = Me.cbDateiname
    '    'MsgBox UCase(Right(Dateiname, 3))
    '    If UCase(Right(Dateiname, 3)) = "HTM" Then
    '        Call sendAusdruckPerEmail(Me.Vorgangtyp, Me.Nummer, """" & Me!Vorgangtyp & """00/000000", Dateiname, Me.cbSofortSenden)
    '        WriteLog(Dateiname, "Email")
    '    Else
    '        MsgBox("Das ist keine HTML Vorlage! Erstellen Sie eine HTML Vorlage !", vbCritical)
    '    End If
    'End Sub

    'Function WriteLog(ByVal Vorlage As String, FunctionName As String) As Boolean
    '    Dim sql As String
    '    sql = "insert into buchVorgaengeAusdruckeLog (Dateiname, Funktion, GedrucktAm) values ('" & Vorlage & "','" & FunctionName & "', now())"
    '    DoCmd.SetWarnings(False)
    '    DoCmd.RunSQL(sql)
    '    DoCmd.SetWarnings(True)
    '    WriteLog = True
    'End Function



    'Private Sub cbDateiname_DblClick(Cancel As Integer)
    '    If UCase(Right(cbDateiname, 3)) = "HTM" Then
    '        Call btnEmail_Click()
    '    Else
    '        Call btnDruck_Click()
    '    End If
    'End Sub

    'Public Sub VorgaengeAusdruck_automateDruck()
    '    Call cbDateiname_DblClick(False)
    'End Sub

    'Private Sub cbLanguageDok_Change()
    '    CURRENT_LANGUAGE_CODE = Me.cbLanguageDok
    'End Sub

    'Private Sub Vorgangtyp_Change()
    '    Debug.Print("OK")
    'End Sub

    Private Sub VorglageListBox_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles VorlageListBox.SelectedIndexChanged
        OK_Button.Enabled = VorlageListBox.SelectedIndex >= 0
        ENGINE_GroupBox.Enabled = OK_Button.Enabled
        SofortSenden_CheckBox.Enabled = OK_Button.Enabled
        btnMailTextSpeichern.Enabled = OK_Button.Enabled
    End Sub

End Class