<%@ Page MaintainScrollPositionOnPostback="true" Title="Title" Language="C#" MasterPageFile="~/Site.Master" %>

<%@ Import Namespace="eDocument.Server.Administrator" %>
<%@ Import Namespace="eDocument.Model" %>

<script runat="server">

    protected void Page_Load(object sender, System.EventArgs e)
    {
        if(!Authorizor.IsAuthorized())
        {
            this.Response.Redirect("~/Forbidden.aspx");
        }

        if(!IsPostBack)
        {
            using (var db = new EdocContext())
            {
                RenderCreate(db);

                var id = Request.QueryString["id"];

                if(!string.IsNullOrWhiteSpace(id))
                    RenderEdit(db, new Guid(id));
            }
        }
    }

    private void RenderEdit(EdocContext db, Guid id)
    {
        var mailReceipt = db.MailReceipts.Single(m => m.Id == id);

        txtName.Text = mailReceipt.Name;
        checkSenderIsOrg.Checked = mailReceipt.IsFromCustomer;
        checkReceipt.Checked = mailReceipt.IsReceipt;

        if(!mailReceipt.IsFromCustomer)
        {
            txtFromAddress.Text = mailReceipt.FromAddress;
            requireFromAddress.Enabled = true;
            txtFromAddress.Enabled = true;
        }
        else
        {
            if(checkSenderIsOrg.Visible)
            {
                var customer = db.Customers.Single(c => c.Id == SessionData.ConsumerID);
                txtFromAddress.Text = customer.EmailAddress;
            }
            txtFromAddress.Enabled = false;
            requireFromAddress.Enabled = false;
        }

        //if(!string.IsNullOrWhiteSpace(mailReceipt.ResponseItems))
        //{
        //    checkXml.Checked = mailReceipt.ResponseItems.Contains("|XML|");
        //    checkPdf.Checked = mailReceipt.ResponseItems.Contains("|PDF|");
        //}

        if(mailReceipt.IsReceipt)
        {
            txtToAddress.Enabled = false;
            requireToAddress.Enabled = false;
        }
        else
        {
            txtToAddress.Text = mailReceipt.ToAddress;
            requireToAddress.Enabled = true;
        }

        checkIsHtml.Checked = mailReceipt.IsHtml;

        var mailReceiptContent = db.MailReceiptContents.First(c => c.MailReceiptId == id);

        txtSubject.Text = mailReceiptContent.Subject;
        txtBody.Text = mailReceiptContent.Body;

        btnCreate.Text = "Oppdater";
    }

    private void RenderCreate(EdocContext db)
    {
        //var customer = db.Customers.Single(c => c.Id == SessionData.ConsumerID);

        //if(!string.IsNullOrWhiteSpace(customer.EmailAddress))
        //{
        //    checkSenderIsOrg.Checked = true;
        //    txtFromAddress.Text = customer.EmailAddress;
        //    txtFromAddress.Enabled = false;
        //}
        //else
        //{
        //    checkSenderIsOrg.Visible = false;
        //}
    }

    private void chkReceipt_CheckedChanged(object sender, EventArgs e)
    {
        txtToAddress.Enabled = !checkReceipt.Checked;
        requireToAddress.Enabled = !checkReceipt.Checked;

        if(checkReceipt.Checked)
            txtToAddress.Text = string.Empty;
    }

    protected void checkSenderIsOrg_CheckedChanged(object sender, EventArgs e)
    {
        txtFromAddress.Enabled = !checkSenderIsOrg.Checked;
        requireFromAddress.Enabled = !checkSenderIsOrg.Checked;

        if(checkSenderIsOrg.Checked)
        {
            using (var db = new EdocContext())
            {
                var customer = db.Customers.Single(c => c.Id == SessionData.ConsumerID);
                txtFromAddress.Text = customer.EmailAddress;
            }
        }
    }

    private void btnCreate_Click(object sender, EventArgs e)
    {
        using (var db = new EdocContext())
        {
            var isEdit = !string.IsNullOrWhiteSpace(Request.QueryString["id"]);

            MailReceipt mailReceipt;

            if(!isEdit)
            {
                mailReceipt = new MailReceipt
                {
                    Id = Guid.NewGuid(),
                };

                db.MailReceipts.Add(mailReceipt);
            }
            else
            {
                var id = new Guid(Request.QueryString["id"]);
                mailReceipt = db.MailReceipts.Single(m => m.Id == id);
            }

            mailReceipt.Name = txtName.Text;
            mailReceipt.CustomerId = SessionData.ConsumerID;
            mailReceipt.IsHtml = checkIsHtml.Checked;

            if(checkSenderIsOrg.Checked)
            {
                mailReceipt.IsFromCustomer = true;
                mailReceipt.FromAddress = null;
            }
            else
            {
                mailReceipt.IsFromCustomer = false;
                mailReceipt.FromAddress = txtFromAddress.Text;
            }

            if(checkReceipt.Checked)
            {
                mailReceipt.IsReceipt = true;
                mailReceipt.ToAddress = null;
            }
            else
            {
                mailReceipt.IsReceipt = false;
                mailReceipt.ToAddress = txtToAddress.Text;
            }

            //var items = new StringBuilder();

            //if(checkPdf.Checked)
            //    items.Append("|PDF|");

            //if(checkXml.Checked)
            //    items.Append("|XML|");

            //mailReceipt.ResponseItems = items.ToString();

            MailReceiptContent mailReceiptContent;

            if(!isEdit)
            {
                mailReceiptContent = new MailReceiptContent
                {
                    Id = Guid.NewGuid(),
                };

                db.MailReceiptContents.Add(mailReceiptContent);
            }
            else
            {
                mailReceiptContent = db.MailReceiptContents.Single(c => c.MailReceiptId == mailReceipt.Id);
            }

            mailReceiptContent.MailReceiptId = mailReceipt.Id;
            mailReceiptContent.Culture = string.Empty;
            mailReceiptContent.Subject = txtSubject.Text;
            mailReceiptContent.Body = txtBody.Text;

            db.SaveChanges();

            Response.Redirect("List.aspx");
        }
    }

</script>

<asp:Content runat="server" ID="Main" ContentPlaceHolderID="MainContent">

    <h1 class="skjema-admin__page-title">
        E-post mal
    </h1>

    <p class="mb-4">
        Fra denne siden kan du opprette/redigere en e-post mal.
    </p>

    <div class="skjema-admin__page__field">
        <label class="skjema-admin__page__label">
            Navn *
        </label>

        <asp:TextBox 
            ID="txtName" 
            CssClass="skjema-admin__page__text"
            runat="server">
        </asp:TextBox>

        <asp:RequiredFieldValidator 
            ForeColor="Red" 
            ID="RequiredFieldValidator1" 
            runat="server" 
            ErrorMessage="*" 
            Display="Dynamic"
            ControlToValidate="txtName">
        </asp:RequiredFieldValidator>
    </div>

    <div class="skjema-admin__page__field">
        <label class="skjema-admin__page__label">
            Mottaker *
        </label>

        <asp:TextBox 
            ID="txtToAddress" 
            CssClass="skjema-admin__page__text mb-4"
            runat="server" 
            Width="208px">
        </asp:TextBox>

        <asp:CheckBox 
            runat="server" 
            AutoPostBack="True" 
            ID="checkReceipt" 
            OnCheckedChanged="chkReceipt_CheckedChanged" 
            Text="Mottaker skal være innsender." />

        <asp:RequiredFieldValidator 
            ID="requireToAddress" 
            ErrorMessage="*" 
            runat="server" 
            ControlToValidate="txtToAddress" 
            ForeColor="Red" 
            Display="Dynamic"/>

        <asp:RegularExpressionValidator 
            runat="server" 
            ControlToValidate="txtToAddress" 
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
            Display="Dynamic" 
            ErrorMessage="Ugyldig e-postadresse" 
            ForeColor="Red">
        </asp:RegularExpressionValidator>
    </div>

    <div class="skjema-admin__page__field">
        <label class="skjema-admin__page__label">
            Avsender *
        </label>

        <asp:TextBox 
            CssClass="skjema-admin__page__text mb-4"
            ID="txtFromAddress" 
            runat="server">
        </asp:TextBox>

        <asp:CheckBox 
            AutoPostBack="True" 
            CssClass="skjema-admin__page__tick"
            Text="Avsender skal være organisasjonen." 
            runat="server" 
            ID="checkSenderIsOrg" 
            OnCheckedChanged="checkSenderIsOrg_CheckedChanged"/>

        <asp:RequiredFieldValidator ForeColor="Red" ID="requireFromAddress" runat="server" ErrorMessage="*" ControlToValidate="txtFromAddress">
        </asp:RequiredFieldValidator>

        <asp:RegularExpressionValidator runat="server" ControlToValidate="txtFromAddress" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic" ErrorMessage="Ugyldig e-postadresse" ForeColor="Red">
        </asp:RegularExpressionValidator>
    </div>

    <div class="skjema-admin__page__field">
        <label class="skjema-admin__page__label">
            Send som HTML
        </label>

        <asp:CheckBox 
             CssClass="skjema-admin__page__tick"
            runat="server" 
            ID="checkIsHtml"/>
    </div>

    <div class="skjema-admin__page__field">
        <label class="skjema-admin__page__label">
            Emne *
        </label>

        <asp:TextBox 
            ID="txtSubject"
            CssClass="skjema-admin__page__text"
            runat="server">
        </asp:TextBox>

        <asp:RequiredFieldValidator 
            ControlToValidate="txtSubject" 
            ForeColor="Red" 
            ID="RequiredFieldValidator3" 
            runat="server" 
            Display="Dynamic"
            ErrorMessage="*">
        </asp:RequiredFieldValidator>
    </div>

    <div class="skjema-admin__page__field">
        <label class="skjema-admin__page__label">
            Meldingstekst *
        </label>

        <asp:TextBox 
            TextMode="MultiLine" 
            CssClass="skjema-admin__page__text"
            ID="txtBody" 
            runat="server" 
            Height="200px">
        </asp:TextBox>

        <asp:RequiredFieldValidator 
            ControlToValidate="txtBody" 
            ForeColor="Red" 
            ID="RequiredFieldValidator4" 
            Display="Dynamic"
            runat="server" 
            ErrorMessage="*">
        </asp:RequiredFieldValidator>
    </div>

	<asp:Button 
        id="btnCreate" 
        runat="server" 
        Text="Opprett" 
        CssClass="skjema-admin__button skjema-admin__button--primary"
        onclick="btnCreate_Click">
	</asp:Button>
</asp:Content>
