﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using MimeKit;

// ReSharper disable once CheckNamespace
namespace AppOMatic.Domain
{
    public class SendMailStep : Step
    {
		public string FromName { get; set; }

		public string FromEmailAddress { get; set; }

		public string ToNameField { get; set; }

		public string ToEmailAddressField { get; set; }

		public string SubjectPattern { get; set; }

		public string BodyPattern { get; set; }

		public bool? BodyIsHtml { get; set; }

	    public SendMailStep()
	    {
		    Name = "SendMail";
	    }

		internal override void Validate(Application application)
		{
			base.Validate(application);

			if(application.SendMailManager == null)
			{
				throw new Exception($"A SendMailStep is included in {application.Name} {application.Version} {application.LifecycleStage}, but no SendMailManager is configurated.");
			}

			if(string.IsNullOrEmpty(FromName)) FromName = application.SendMailManager.FromName;
			if(string.IsNullOrEmpty(FromEmailAddress)) FromEmailAddress = application.SendMailManager.FromEmailAddress;
			if(string.IsNullOrEmpty(ToNameField)) ToNameField = application.SendMailManager.ToNameField;
			if(string.IsNullOrEmpty(ToEmailAddressField)) ToEmailAddressField = application.SendMailManager.ToEmailAddressField;
			if(string.IsNullOrEmpty(SubjectPattern)) SubjectPattern = application.SendMailManager.SubjectPattern;
			if(string.IsNullOrEmpty(BodyPattern)) BodyPattern = application.SendMailManager.BodyPattern;
			if(BodyIsHtml == null) BodyIsHtml = application.SendMailManager.BodyIsHtml;
		}

		internal override Task HandleAsync(EndPoint endPoint, IDictionary<string, object> endPointContext, HttpContext context, DataObject dobj)
		{
			var message = new MimeMessage
			{
				Body = new TextPart(BodyIsHtml.Value ? "html" : "plain") { Text = dobj.Format(BodyPattern) },
				Date = DateTime.UtcNow,
				Subject = dobj.Format(SubjectPattern),
			};

			message.From.Add(new MailboxAddress(Encoding.UTF8, FromName, FromEmailAddress));

			var toName = dobj.Get<string>(ToNameField);
			var toAddress = dobj.Get<string>(ToEmailAddressField);

			if(string.IsNullOrEmpty(toName))
			{
				throw new Exception($"Trying to send e-mail but field {ToNameField} (ToNameField) does not have a value");
			}

			if(string.IsNullOrEmpty(toAddress))
			{
				throw new Exception($"Trying to send e-mail but field {toAddress} (ToEmailAddressField) does not have a value");
			}

			message.To.Add(new MailboxAddress(Encoding.UTF8, toName, toAddress));

			return endPoint.Application.SendMailManager.SendAsync(message);
		}
	}
}
