Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Database
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient

Public Class EmailFunctions
    Private ReadOnly _logConfig As LogConfig
    Private ReadOnly _logger As Logger
    Private ReadOnly _mssql As MSSQLServer
    Private ReadOnly _firebird As Firebird

    Public Sub New(LogConfig As LogConfig, MSSQL As MSSQLServer, Firebird As Firebird)
        _logConfig = LogConfig
        _logger = _logConfig.GetLogger()
        _mssql = MSSQL
        _firebird = Firebird
    End Sub

    Public Sub AddToEmailQueueFB(MessageId As String, BodyText As String, EmailData As EmailData, NamePortal As String)
        If EmailData Is Nothing Then
            _logger.Warn("EmailData is empty. Email will not be sent!")
            Exit Sub
        End If

        Try
            Dim oJobId = RandomValue(1, 10000)
            Dim oReference = MessageId
            Dim oEmailTo = ""
            Dim oSubject = EmailStrings.EMAIL_SUBJECT_REJECTED.Replace(EmailStrings.constNAME_ZUGFERD_PORTAL, NamePortal)
            Dim oAccountId = 1
            Dim oCreatedWho = "ZUGFeRD Service"
            Dim oFinalBodyText = String.Format(EmailStrings.EMAIL_WRAPPING_TEXT.Replace(EmailStrings.constNAME_ZUGFERD_PORTAL, NamePortal), BodyText)

            Dim oEmailAddress = EmailData.From
            Dim oAttachment = EmailData.Attachment

            If IsNothing(oEmailAddress) OrElse String.IsNullOrWhiteSpace(oEmailAddress) Then
                _logger.Warn("Could not find email-address for MessageId {0}", MessageId)
                oEmailTo = String.Empty
            Else
                oEmailTo = oEmailAddress
            End If

            _logger.Debug("Generated Email:")
            _logger.Debug("To: {0}", oEmailTo)
            _logger.Debug("Subject: {0}", oSubject)
            _logger.Debug("Body {0}", oFinalBodyText)
            Dim osql = $"select * from TBEDM_EMAIL_QUEUE where REFERENCE1 = '{oReference} and EMAIL_TO = ''{oEmailTo}' and EMAIL_SUBJ = '{oSubject}'"

            Dim oDTResult As DataTable = _firebird.GetDatatable(osql)

            If oDTResult.Rows.Count = 0 Then
                Dim oSQLInsert = $"INSERT INTO TBEDM_EMAIL_QUEUE "
                oSQLInsert &= "(JOB_ID, REFERENCE1, EMAIL_ACCOUNT_ID, EMAIL_TO, EMAIL_SUBJ, EMAIL_BODY, CREATEDWHO, EMAIL_ATTMT1) VALUES "
                oSQLInsert &= $"({oJobId}, '{oReference}', {oAccountId}, '{oEmailTo}', '{oSubject}', '{oFinalBodyText.Replace("'", "''")}', '{oCreatedWho}', '{oAttachment}')"
                _firebird.ExecuteNonQuery(oSQLInsert)
                _logger.Debug("Email Queue updated for MessageId {0}.", MessageId, oEmailTo)
            Else
                _logger.Debug("Email has already been sent!!")
            End If
        Catch ex As Exception
            _logger.Error(ex)
        End Try
    End Sub
    Public Sub AddToEmailQueueMSSQL(MessageId As String, BodyText As String, pEmailData As EmailData, SourceProcedure As String, pEmailAccountId As Integer, NamePortal As String)
        If pEmailData Is Nothing Then
            _logger.Warn("EmailData is empty. Email will not be sent!")
            Exit Sub
        End If

        Try
            Dim oJobId = RandomValue(1, 10000)
            Dim oReference = MessageId
            Dim oEmailTo = ""
            Dim oSubject = EmailStrings.EMAIL_SUBJECT_REJECTED.Replace(EmailStrings.constNAME_ZUGFERD_PORTAL, NamePortal)
            Dim oCreatedWho = "ZUGFeRD Service"

            Dim oMaskedBodyText = BodyText.Replace("'", "''")
            Dim oSubjectBodyText = String.Format(EmailStrings.EMAIL_SUBJECT_TEXT.Replace(EmailStrings.constNAME_ZUGFERD_PORTAL, NamePortal), pEmailData.Subject).Replace("'", "''")
            Dim oCompleteBodyText = oMaskedBodyText & oSubjectBodyText

            Dim oFinalBodyText = String.Format(EmailStrings.EMAIL_WRAPPING_TEXT.Replace(EmailStrings.constNAME_ZUGFERD_PORTAL, NamePortal), oCompleteBodyText)

            Dim oEmailAddress = pEmailData.From
            Dim oAttachment = pEmailData.Attachment
            If oAttachment <> String.Empty Then
                _logger.Debug($"Attachment_String [{oAttachment}]!")
                If IO.File.Exists(oAttachment) = False Then
                    _logger.Info($"Attachment.File [{oAttachment}] is not existing!!!")
                End If
            End If

            If IsNothing(oEmailAddress) OrElse String.IsNullOrWhiteSpace(oEmailAddress) Then
                _logger.Warn("Could not find email-address for MessageId {0}", MessageId)
                oEmailTo = String.Empty
            Else
                oEmailTo = oEmailAddress
            End If

            _logger.Debug("Generated Email:")
            _logger.Debug("To: {0}", oEmailTo)
            _logger.Debug("Subject: {0}", oSubject)
            _logger.Debug("Body {0}", oFinalBodyText)
            Dim osql = $"Select MAX(GUID) FROM TBEMLP_HISTORY WHERE EMAIL_MSGID = '{MessageId}'"
            Dim oHistoryID = _mssql.GetScalarValue(osql)

            'osql = $"select * from TBEMLP_EMAIL_OUT where REFERENCE_ID = {oHistoryID} and EMAIL_ADRESS = '{oEmailTo}' and EMAIL_SUBJ = '{oSubject}'"

            'Dim oDTResult As DataTable = _mssql.GetDatatable(osql)

            If IsNumeric(oHistoryID) Then
                Dim oInsert = $"INSERT INTO [dbo].[TBEMLP_EMAIL_OUT] (
                        [REMINDER_TYPE_ID]
                       ,[SENDING_PROFILE]
                       ,[REFERENCE_ID]
                       ,[REFERENCE_STRING]
                       ,[WF_ID]
                       ,[EMAIL_ADRESS]
                       ,[EMAIL_SUBJ]
                       ,[EMAIL_BODY]
                       ,[COMMENT]
                       ,[ADDED_WHO]
                        ,EMAIL_ATTMT1)
                 VALUES
                       (77
                       ,{pEmailAccountId}
                       ,{oHistoryID}
                       ,'{MessageId}'
                       ,77
                       ,'{oEmailTo}'
                       ,'{oSubject}'
                       ,'{oFinalBodyText}'
                       ,'{SourceProcedure}'
                       ,'{oCreatedWho}'
                       ,'{oAttachment}')"
                _mssql.ExecuteNonQuery(oInsert)
            Else
                'If oDTResult.Rows.Count = 0 Then
                '    _logger.Debug("Email has already been sent!!")
                'Else
                _logger.Warn("Could not get oHistoryID in AddToEmailQueueMSSQL!!")
                ' End If
            End If
        Catch ex As Exception
            _logger.Error(ex)
        End Try
    End Sub

    Public Function GetEmailDataForMessageId(MessageId As String) As EmailData
        Dim oSQL = $"SELECT EMAIL_FROM, EMAIL_SUBJECT, EMAIL_ATTMT1 FROM TBEDM_EMAIL_PROFILER_HISTORY WHERE EMAIL_MSGID = '{MessageId}'"
        Try
            Dim oDatatable = _firebird.GetDatatable(oSQL)
            Dim oRow As DataRow

            If oDatatable.Rows.Count = 0 Then
                _logger.Warn("Got no results for MessageId {0}", MessageId)
                Return Nothing
            ElseIf oDatatable.Rows.Count > 1 Then
                _logger.Warn("Got too many results for MessageId {0}. Using last row.", MessageId)
            End If

            _logger.Debug("Got Email Data for FileId {0}", MessageId)
            oRow = oDatatable.Rows.Item(oDatatable.Rows.Count - 1)

            Return New EmailData() With {
                .From = oRow.Item("EMAIL_FROM"),
                .Attachment = oRow.Item("EMAIL_ATTMT1"),
                .Subject = oRow.Item("EMAIL_SUBJECT")
            }
        Catch ex As Exception
            _logger.Warn("Could not fetch Email Data for FileId {0}", MessageId)
            Return Nothing
        End Try
    End Function

    Public Function GetOriginalEmailPath(OriginalEmailDirectory As String, MessageId As String) As String
        Dim oAttachmentDirectory = OriginalEmailDirectory
        Dim oAttachmentFile = MessageId & ".eml"
        Dim oAttachmentPath = Path.Combine(oAttachmentDirectory, oAttachmentFile)

        If File.Exists(oAttachmentPath) Then
            Return oAttachmentPath
        Else
            _logger.Warn("Email File {0} does not exist. Empty String will be returned.", oAttachmentPath)
            Return String.Empty
        End If
    End Function

    Public Function GetEmailPathWithSubjectAsName(RejectedEmailDirectory As String, UncleanedSubject As String) As String
        Dim oCleanSubject = String.Join("", UncleanedSubject.Split(Path.GetInvalidPathChars()))
        Dim oAttachmentDirectory = RejectedEmailDirectory
        Dim oAttachmentFile = oCleanSubject & ".eml"
        Dim oAttachmentPath = Path.Combine(oAttachmentDirectory, oAttachmentFile)

        Return oAttachmentPath
    End Function

    Private Function RandomValue(lowerBound As Integer, upperBound As Integer) As Integer
        Dim oRandomValue = CInt(Math.Floor((upperBound - lowerBound + 1) * Rnd())) + lowerBound
        Return oRandomValue
    End Function
End Class
