Imports CharterDotCom.CommonEntities.Library.Enumerations
Imports CharterDotCom.CommonEntities.Library
Imports CharterDotCom.WebSite.Library

Partial Class Customers_EmailArticle
    Inherits CharterCMSPage 'JPIRKEY 4-2010 Updating all pages to inherit from a single source.

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim articleTitle As String = ""

            Me.txtSubject.Text = GetSubject(articleTitle)
            Me.txtBody.Text = GetBody(articleTitle, Environment.NewLine)

            Me.txtTo.Focus()
            Me.txtTo.Attributes.Add("onfocusin", " select();")
            Me.txtSubject.Attributes.Add("onfocusin", " blur;")
            Me.txtBody.Attributes.Add("onfocusin", " blur;")
        End If
    End Sub

    Protected Sub closeBut_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles closeBut.Click
        RedirectTo("support")
    End Sub

    Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSend.Click

        Dim fromEmail As String
        Dim toEmail As String
        Dim emailSubject As String
        Dim emailBody As String
        Dim articleTitle As String = ""

        fromEmail = ContentManager.Instance.GetContent("Support:EmailThisArticle:FromEmailAddress", "1", OwnerType.Other)
    
        If Not ValidEmail(Me.txtTo.Text) Then
            lblError.Text = "Recipient email address is invalid."
            Return
        End If

        ' issue 17789
        ' limit the number of recipients
        If Not ValidRecipientCount(txtTo.Text) Then
            lblError.Text = "A maximum of 5 recipients can be specified."
            Return
        End If

        'validate From email
        If (chkCC.Checked) Then
            If Not ValidEmail(Me.txtFrom.Text) Then
                lblError.Text = "Your email address is invalid."
                Return
            End If
        End If

        ' issue 17789
        ' limit how often a user can send mail from this page
        If ValidWait(lblError) Then
        Else
            Return
        End If

        toEmail = txtTo.Text

        articleTitle = ""
        emailSubject = GetSubject(articleTitle)
        emailBody = GetBody(articleTitle, "<BR>")

        ' issue 17789
        ' add article title to message body
        If txtFrom.Text.Trim.Length > 0 And txtFrom.Text.Trim <> "Enter your email address" Then
            emailBody = "From: " & txtFrom.Text.Trim.ToString() & "<br><br>" & emailBody
        End If

        SendEmail(fromEmail, toEmail, emailSubject, emailBody)
        Session("Last_Email_Article_Sent") = DateTime.Now

        'Send email to sender (this is required because SendEmail method in the provider not supporting 
        'multiple emails)
        If chkCC.Checked Then
            If Me.txtFrom.Text <> "Enter your email address" And _
                Me.txtFrom.Text <> "" And _
                ValidEmail(Me.txtFrom.Text) Then
                SendEmail(fromEmail, Me.txtFrom.Text, emailSubject, emailBody)
            End If
        End If

        RedirectTo("emailsent")

    End Sub

    ' issue 17789
    Private Function GetSubject(ByRef articleTitle As String) As String
        Dim emailSubject As String = ""

        If Not Request.QueryString("title") Is Nothing Then
            articleTitle = Request.QueryString("title")
        End If
        emailSubject = ContentManager.Instance.GetContent("Support:EmailThisArticle:Subject", "1", OwnerType.Other)
        emailSubject = emailSubject.Replace("{ArticleTitle}", articleTitle)

        Return emailSubject

    End Function

    Private Function GetBody(ByVal articleTitle As String, ByVal psReplacementString As String) As String
        Dim emailBody As String = ""
        Dim supportURL As String = ""

        emailBody = ContentManager.Instance.GetContent("Support:EmailThisArticle:Message", "1", OwnerType.Other)

        supportURL = Request.Url.AbsoluteUri.ToString().ToLower().Replace("emailarticle.aspx", "support.aspx")

        If Not (supportURL Is Nothing) Then
            'replace place holder {articleURLPlaceHolder} with URL
            emailBody = emailBody.Replace("{articleURLPlaceHolder}", supportURL)
        Else
            emailBody = emailBody.Replace("{articleURLPlaceHolder}", "")
        End If

        emailBody = emailBody.Replace("$$$", psReplacementString)

        ' issue 17789
        ' add article title to message body
        If Not (String.IsNullOrEmpty(articleTitle)) Then
            emailBody = "The sender listed above has chosen to share this charter.com support content:  " & _
                    articleTitle & psReplacementString & _
                    emailBody
        End If

        Return emailBody

    End Function

    Private Function ValidEmail(ByVal email As String) As Boolean
        Return System.Text.RegularExpressions.Regex.IsMatch(email, "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")
    End Function

    ' issue 17789
    ' Limit how often a user can send emails from this page
    Private Function ValidWait(ByVal poLblError As Label) As Boolean

        Dim oSec As Object = Application("EMAIL_WAIT_SECONDS")

        Dim lWaitPeriod As Long = 10
        If Not (oSec Is Nothing) AndAlso _
            (oSec.ToString().Trim() <> "") AndAlso _
            (IsNumeric(oSec.ToString().Trim())) Then
            lWaitPeriod = CLng(oSec.ToString().Trim())
        End If

        If IsNothing(Session("Last_Email_Article_Sent")) OrElse _
          (Not (IsDate(Session("Last_Email_Article_Sent")))) Then
            ' none sent yet 
            Return True
        End If

        ' number of seconds between last-sent email and current date/time is too short
        If Math.Abs(DateDiff(DateInterval.Second, Session("Last_Email_Article_Sent"), DateTime.Now)) < lWaitPeriod Then
            poLblError.Text = "We are unable to respond to your email request at this time.  Please try again later."
            Return False
        End If

        Return True
    End Function

    ' issue 17789
    ' limit the number of recipients that can be specified in the TO address of the email
    Private Function ValidRecipientCount(ByVal email As String) As Boolean
        Dim Recipients() As String = Nothing
        Dim lMaxRecipients As Long = 5
        Dim oMax As Object = Application("EMAIL_RECIPIENTLIST_SIZE")
        If String.IsNullOrEmpty(email) Then
            ' must specify at least ONE recipient
            Return False
        End If

        ' issue 17789
        ' note that this requires adding new rows to the WebConfig table
        ' using the key name EMAIL_RECIPIENTLIST_SIZE
        If Not (oMax Is Nothing) AndAlso _
            (oMax.ToString().Trim() <> "") AndAlso _
            (IsNumeric(oMax.ToString().Trim())) Then
            lMaxRecipients = CLng(oMax.ToString().Trim())
        End If

        ' three possible items used to separate email addresses - space, semicolon, comma
        If email.IndexOf(" ") > -1 Then
            Recipients = email.Split(" ")
        Else
            If email.IndexOf(";") > -1 Then
                Recipients = email.Split(";")
            Else
                If email.IndexOf(",") > -1 Then
                    Recipients = email.Split(",")
                Else
                    ' only one email address
                    Return True
                End If
            End If
        End If

        If Recipients.GetLength(0) > lMaxRecipients Then
            Return False
        End If

        Return True

    End Function

    Private Sub SendEmail(ByVal fromEmail As String, ByVal toEmail As String, ByVal subject As String, ByVal body As String)
        Try
            Dim iMail As ISupportProvider = CType(Activator.GetObject(GetType(ISupportProvider), CStr(System.Web.HttpContext.Current.Application("RemoteURL_SupportProvider"))), ISupportProvider)
            iMail.SendEMail(fromEmail, toEmail, subject, body.ToString, True)
        Catch ex As Exception
            'TODO handle exception
        End Try
    End Sub

    Private Sub RedirectTo(ByVal redirectTo As String)
        Dim articleID As String
        articleID = Request.QueryString("supportarticleid")
        If redirectTo = "support" Then
            Response.Redirect("Support.aspx?supportarticleid=" + articleID)
        ElseIf redirectTo = "emailsent" Then
            Response.Redirect("EmailArticleSent.aspx?supportarticleid=" + articleID)
        End If
    End Sub

End Class