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 emailSubject As String
            Dim emailBody As String
            Dim supportURL As String = ""
            Dim articleTitle 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)

            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

            Me.txtSubject.Text = emailSubject
            ' issue 17789
            ' add article title to message body
            If Not (String.IsNullOrEmpty(articleTitle)) Then
                Me.txtBody.Text = "The sender listed above has chosen to share this charter.com support content:" & articleTitle & Environment.NewLine & emailBody
            Else
                Me.txtBody.Text = emailBody
            End If

            Me.txtTo.Focus()
            Me.txtTo.Attributes.Add("onfocusin", " select();")
        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, toEmail As String, emailSubject As String, emailBody As String

        fromEmail = ContentManager.Instance.GetContent("Support:EmailThisArticle:FromEmailAddress", "1", OwnerType.Other)
        emailSubject = txtSubject.Text

        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."
        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

        'TODO: validate email
        toEmail = txtTo.Text

        emailBody = txtBody.Text
        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)

        '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

    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 lWaitPeriod As Long = 10
        If Not (Application("EMAIL_WAIT_SECONDS") Is Nothing) AndAlso _
            (Application("EMAIL_WAIT_SECONDS").ToString().Trim() <> "") AndAlso _
            (IsNumeric(Application("EMAIL_WAIT_SECONDS").ToString().Trim())) Then
            lWaitPeriod = CLng(Application("EMAIL_WAIT_SECONDS").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 = "Emails can only be sent every " & _
                            lWaitPeriod & _
                            " seconds."
            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

        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 (Application("EMAIL_RECIPIENTLIST_SIZE") Is Nothing) AndAlso _
            (Application("EMAIL_RECIPIENTLIST_SIZE").ToString().Trim() <> "") AndAlso _
            (IsNumeric(Application("EMAIL_RECIPIENTLIST_SIZE").ToString().Trim())) Then
            lMaxRecipients = CLng(Application("EMAIL_RECIPIENTLIST_SIZE").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

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

    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
