using System;
using System.Text;
using System.Collections.Generic;
using rockfishCore.Models;
using rockfishCore.Util;

using MailKit.Net.Imap;
using MailKit.Search;
using MailKit;
using MimeKit;




namespace rockfishCore.Util
{
    //Trial Key request handler
    public static class TrialKeyRequestHandler
    {
        //non anonymous return object for array
        //https://stackoverflow.com/a/3202396
        private class retObject
        {
            public string from;
            public string subject;
            public string date;
            public uint uid;
        }

        //MAILKIT DOCS
        //https://github.com/jstedfast/MailKit#using-mailkit

        public static dynamic Requests()
        {
            try
            {
                List<retObject> ret = new List<retObject>();
                List<RfMail.rfMailMessage> msgs = RfMail.GetMessages(SearchQuery.SubjectContains("Request for 30 day temporary").And(SearchQuery.NotAnswered).And(SearchQuery.NotDeleted));


                foreach (RfMail.rfMailMessage m in msgs)
                {
                    ret.Add(new retObject()
                    {
                        uid = m.uid,
                        subject = m.message.Subject,
                        date = m.message.Date.LocalDateTime.ToString("g"),
                        from = m.message.From.ToString()
                    });
                }


                return new { ok = 1, requests = ret };
            }
            catch (Exception e)
            {
                return new
                {
                    error = 1,
                    msg = "Error @ TrialKeyRequestHandler->Requests()",
                    error_detail = new { message = e.Message, stack = e.StackTrace }
                };
            }
        }//requests




        public static dynamic GenerateFromRequest(uint uid, LicenseTemplates licenseTemplates, string authUser, rockfishContext ct)
        {
            try
            {
                using (var client = new ImapClient())
                {
                    var m = RfMail.GetMessage(uid);

                    string greetingReplySubject = "re: " + m.Subject;

                    //Extract request message fields
                    string replyTo = m.From.ToString();

                    //get request message body
                    string request = m.TextBody;

                    //Parse request message for deets                   
                    if (string.IsNullOrWhiteSpace(request))
                    {
                        throw new System.NotSupportedException("TrialKeyRequestHandler->GenerateFromRequest: error text body of request email is empty");
                    }
                    bool bLite = m.Subject.Contains("AyaNova Lite");
                    int nNameStart = request.IndexOf("Name:\r\n") + 7;
                    int nNameEnd = request.IndexOf("Company:\r\n");
                    int nCompanyStart = nNameEnd + 10;
                    int nCompanyEnd = request.IndexOf("Referrer:\r\n");
                    string sName = request.Substring(nNameStart, nNameEnd - nNameStart).Trim();
                    if (sName.Contains(" "))
                        sName = sName.Split(' ')[0];
                    string sRegTo = request.Substring(nCompanyStart, nCompanyEnd - nCompanyStart).Trim();

                    //make keycode                     
                    string keyCode = KeyFactory.GetTrialKey(sRegTo, bLite, licenseTemplates, authUser, replyTo, ct);//case 3233

                    //get greeting and subject
                    string greeting = string.Empty;
                    string keyEmailSubject = string.Empty;

                    if (bLite)
                    {
                        //No lite trial greeting but text looks ok to just use full trial greeting so going with that
                        //(the column is in the DB but there is no UI for it and it's null)
                        //greeting = licenseTemplates.LiteTrialGreeting.Replace("[FirstName]", sName);
                        greeting = licenseTemplates.FullTrialGreeting.Replace("[FirstName]", sName);
                        keyEmailSubject = "AyaNova Lite and all add-ons temporary 30 day Activation key";
                    }
                    else
                    {
                        greeting = licenseTemplates.FullTrialGreeting.Replace("[FirstName]", sName);
                        keyEmailSubject = "AyaNova and all add-on's temporary 30 day Activation key";
                    }

                    return new
                    {
                        ok = 1,
                        uid = uid,
                        requestReplyToAddress = replyTo,
                        requestFromReplySubject = keyEmailSubject,
                        requestKeyIsLite = bLite,
                        keycode = keyCode,
                        greeting = greeting,
                        greetingReplySubject = greetingReplySubject,
                        request = request
                    };
                }
            }
            catch (Exception e)
            {

                return new
                {
                    error = 1,
                    ok = 0,
                    msg = "Error @ TrialKeyRequestHandler->GenerateFromRequest()",
                    error_detail = new { message = e.Message, stack = e.StackTrace }
                };
            }
        }//requests


        public static dynamic SendTrialRequestResponse(dtoKeyRequestResponse k)
        {
            try
            {
                //-----------------
                //Send both responses

                //Send the greeting email
                RfMail.SendMessage("support@ayanova.com", k.requestReplyToAddress, k.greetingReplySubject, k.greeting, true, "MsgType", "TrialRequestGreet");

                //Send the license key email
                RfMail.SendMessage("support@ayanova.com", k.requestReplyToAddress, k.requestFromReplySubject, k.keycode, true, "MsgType", "TrialRequestKey");

                // Flag original request message as read and replied
                RfMail.FlagInboxMessageSeenReplied(k.request_email_uid);


                //------------------
                return new { ok = 1 };
            }
            catch (Exception e)
            {
                return new
                {
                    error = 1,
                    msg = "Error @ TrialKeyRequestHandler->SendTrialRequestResponse()",
                    error_detail = new { message = e.Message, stack = e.StackTrace }
                };
            }
        }//requests


    }//eoc

}//eons