context: using CmsData;
  using CmsWeb.Lifecycle;
  using CmsWeb.Models;
  using Dapper;
  using Elmah;
  using RestSharp;
  using System;
  using System.Configuration;
  using System.Data.SqlClient;
  using System.Globalization;
  using System.Linq;
  using System.Net;
  using System.Text.RegularExpressions;
  using System.Threading;
  using System.Web.Hosting;
  using System.Web.Mvc;
  using UtilityExtensions;
  
  namespace CmsWeb.Areas.Manage.Controllers
  {
      [RouteArea("Manage"), Route("~/Manage/Emails/{action}/{id?}")]
      public class EmailsController : CmsController
      {
          public EmailsController(IRequestManager requestManager) : base(requestManager)
          {
          }
  
          [Route("~/Emails")]
          public ActionResult Index()
          {
              var m = new EmailsModel();
              return View(m);
          }
  
          public ActionResult SentBy(int? id)
          {
              var m = new EmailsModel { senderid = id };
              return View("Index", m);
          }
  
          public ActionResult SentTo(int? id)
          {
              var m = new EmailsModel { peopleid = id };
              return View("Index", m);
          }
  
          [Route("~/Emails/Details/{id:int}")]
          [Route("~/Manage/Emails/Details/{id:int}")]
          public ActionResult Details(int id)
          {
              var m = new EmailModel(id);
              if (m.queue == null)
              {
                  return Content("no email found");
              }
  
              var curruser = CurrentDatabase.LoadPersonById(CurrentDatabase.UserPeopleId ?? 0);
              if (curruser == null)
              {
                  return Content("no user");
              }
  
              if (User.IsInRole("Admin")
                  || User.IsInRole("ManageEmails")
                  || User.IsInRole("Finance")
                  || m.queue.FromAddr == curruser.EmailAddress
                  || m.queue.QueuedBy == curruser.PeopleId
                  || m.queue.EmailQueueTos.Any(et => et.PeopleId == curruser.PeopleId))
              {
                  return View(m);
              }
  
              return Content("not authorized");
          }
  
          public ActionResult SeeHtml(int id)
          {
              var m = new EmailModel(id);
              if (m.queue == null)
              {
                  return Content("no email found");
              }
  
              var curruser = CurrentDatabase.LoadPersonById(CurrentDatabase.UserPeopleId ?? 0);
              if (curruser == null)
              {
                  return Content("no user");
              }
  
              if (User.IsInRole("Admin")
                  || User.IsInRole("ManageEmails")
                  || User.IsInRole("Finance")
                  || m.queue.FromAddr == curruser.EmailAddress
                  || m.queue.QueuedBy == curruser.PeopleId
                  || m.queue.EmailQueueTos.Any(et => et.PeopleId == curruser.PeopleId))
              {
                  return View(m);
              }
  
              return Content("not authorized");
          }
  
          public ActionResult GetEmailBody(string id)
          {
              var m = new EmailModel(id.ToInt());
              if (m.queue == null)
              {
                  return Content("no email found");
              }
  
              var curruser = CurrentDatabase.LoadPersonById(CurrentDatabase.UserPeopleId ?? 0);
              if (curruser == null)
              {
                  return Content("no user");
              }
  
              if (User.IsInRole("Admin")
                  || User.IsInRole("ManageEmails")
                  || User.IsInRole("Finance")
                  || m.queue.FromAddr == curruser.EmailAddress
                  || m.queue.QueuedBy == curruser.PeopleId
                  || m.queue.EmailQueueTos.Any(et => et.PeopleId == curruser.PeopleId))
              {
                  return Content(m.queue.Body);
              }
  
              return Content("not authorized");
          }
  
          public ActionResult ConvertToSearch(int id)
          {
              var cc = CurrentDatabase.ScratchPadCondition();
              cc.Reset();
              cc.AddNewClause(QueryType.EmailRecipient, CompareType.Equal, id);
              cc.Save(CurrentDatabase);
              return Redirect("/Query/" + cc.Id);
          }
  
          public ActionResult Tracking(int id)
          {
              ViewBag.emailID = id;
              return View();
          }
  
          [Authorize(Roles = "Developer")]
          public ActionResult SendNow(int id)
          {
              string host = CurrentDatabase.Host;
              // save these from HttpContext to set again inside thread local storage
              var useremail = Util.UserEmail;
              var isinroleemailtest = User.IsInRole("EmailTest");
  
              HostingEnvironment.QueueBackgroundWorkItem(ct =>
              {
                  try
                  {
                      var db = CMSDataContext.Create(host);
                      var cul = CurrentDatabase.Setting("Culture", "en-US");
                      Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul);
                      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cul);
                      // set these again inside thread local storage
                      Util.UserEmail = useremail;
                      Util.IsInRoleEmailTest = isinroleemailtest;
                      db.SendPeopleEmail(id);
                  }
                  catch (Exception ex)
                  {
                      var ex2 = new Exception("Emailing error for queueid " + id, ex);
                      ErrorLog errorLog = ErrorLog.GetDefault(null);
                      errorLog.Log(new Error(ex2));
  
                      var db = CMSDataContext.Create(host);
                      var equeue = db.EmailQueues.Single(ee => ee.Id == id);
                      equeue.Error = ex.Message.Truncate(200);
                      db.SubmitChanges();
                  }
              });
              return Redirect("/Emails/Details/" + id);
          }
  
          public ActionResult DeleteQueued(int id)
          {
              var m = new EmailModel(id);
              if (m.queue == null)
              {
                  return Redirect("/Emails");
              }
  
              if (m.queue.Sent.HasValue || !m.queue.SendWhen.HasValue || !m.CanDelete())
              {
                  return Redirect("/");
              }
  
              DeleteEmail(id);
              return Redirect("/Emails");
          }
  
          private static void DeleteEmail(int id)
          {
              var cn = new SqlConnection(Util.ConnectionString);
              cn.Open();
              cn.Execute(@"
                  DELETE dbo.EmailLinks WHERE EmailID = @id;
                  DELETE dbo.EmailResponses WHERE Id = @id;
                  DELETE dbo.EmailQueueTo WHERE Id = @id;
                  DELETE dbo.EmailQueue WHERE Id = @id;
  
gt:                 ", new { id });