namespace Hims.Api.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
    using System.Threading.Tasks;
    using Domain.Configurations;
    using Domain.Helpers;
    using Domain.Services;
    using Hims.Api.Models;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Models.Ticket;
    using Models.Ticket.Performance;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;
    using Senders;
    using Shared.DataFilters;
    using Shared.EntityModels;
    using Shared.Library;
    using Shared.Library.Enums;
    using Utilities;

    /// <inheritdoc />
    [Route("api/tickets")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class TicketsController : BaseController
    {
        /// <summary>
        /// The ticket service.
        /// </summary>
        private readonly ITicketService ticketService;

        /// <summary>
        /// The sms sender.
        /// </summary>
        private readonly ISMSSender smsSender;

        /// <summary>
        /// The patient document services.
        /// </summary>
        private readonly IPatientDocumentService patientDocumentServices;

        /// <summary>
        /// The amazon s3 helper.
        /// </summary>
        private readonly IDocumentHelper documentHelper;

        /// <summary>
        /// The account service.
        /// </summary>
        private readonly IAccountService accountService;

        /// <summary>
        /// The aes helper.
        /// </summary>
        private readonly IAESHelper aesHelper;

        /// <summary>
        /// The amazon s 3 configuration.
        /// </summary>
        private readonly IAmazonS3Configuration amazonS3Configuration;

        /// <summary>
        /// The email sender.
        /// </summary>
        private readonly IEmailSender emailSender;

        /// <inheritdoc />
        public TicketsController(ITicketService ticketService, ISMSSender smsSender, IAESHelper aesHelper, IPatientDocumentService patientDocumentServices, IDocumentHelper documentHelper, IAccountService accountService, IAmazonS3Configuration amazonS3Configuration, IEmailSender emailSender)
        {
            this.ticketService = ticketService;
            this.smsSender = smsSender;
            this.aesHelper = aesHelper;
            this.patientDocumentServices = patientDocumentServices;
            this.documentHelper = documentHelper;
            this.accountService = accountService;
            this.amazonS3Configuration = amazonS3Configuration;
            this.emailSender = emailSender;
        }

        /// <summary>
        /// The check account async.
        /// </summary>
        /// <param name="mobile">
        /// The mobile.
        /// </param>
        /// <param name="roleId">
        /// The role id.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpGet]
        [AllowAnonymous]
        [Route("check-user")]
        public async Task<ActionResult> CheckAccountAsync(string mobile, int roleId)
        {
            if (string.IsNullOrEmpty(mobile))
            {
                return this.BadRequest("Invalid Mobile number.");
            }

            var account = await this.ticketService.CheckAccountExists(mobile, roleId);
            return this.Success(account);
        }

        /// <summary>
        /// The get support categories.
        /// </summary>
        /// <param name="isExist">
        /// The is exist.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpGet]
        [AllowAnonymous]
        [Route("get-categories")]
        public async Task<ActionResult> GetSupportCategory(bool? isExist)
        {
            var account = await this.ticketService.GetSupportCategories(isExist);
            return this.Success(account);
        }

        /// <summary>
        /// The create ticket async.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly", Justification = "Reviewed. Suppression is OK here.")]
        [HttpPost]
        [AllowAnonymous]
        [Route("generate-ticket")]
        [Consumes("multipart/form-data")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(417)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> CreateTicketAsync([FromForm] TicketModel model, [FromHeader] LocationHeader header)
        {
            model = (TicketModel)EmptyFilter.Handler(model);
            model.LocationId = !string.IsNullOrEmpty(header.LocationId) ? int.Parse(header.LocationId) != 0 ? int.Parse(header.LocationId) : (int?)null : (int?) null;
            var files = this.Request.Form.Files;

            var urls = new List<Attachments>();

            if (files.Count != 0)
            {
                if (files.Count > 10)
                {
                    return this.BadRequest("Maximum of 10 files can be allowed to upload.");
                }

                var contentTypes = this.documentHelper.FetchContentTypes().ToList();

                if (!ListFilter.ContainsAll(contentTypes, files.Select(m => m.ContentType).Distinct()))
                {
                    return this.Failed($"Only {string.Join(", ", contentTypes)} files are allowed.");
                }

                var guid = Guid.Empty;
                var account = new UserAccount();

                if (model.RaisedBy != null && model.RaisedBy != 0)
                {
                    account = await this.accountService.FindAsync((int)model.RaisedBy);
                    guid = await this.accountService.FindGuidAsync(account.ReferenceId, Roles.Patient);
                }

                var index = 0;
                var patientDocuments = new List<PatientDocumentModel>();
                foreach (var file in files)
                {
                    var fileName = $"attachment_{index}_{DateTime.UtcNow.Ticks}{System.IO.Path.GetExtension(file.FileName)}";
                    string fileUrl = string.Empty;
                    if (guid != Guid.Empty)
                    {
                        if (model.RaisedBy != null)
                        {
                            var document = new PatientDocumentModel
                            {
                                DocumentType = "Others",
                                Description = null,
                                DocumentName = $@"attachment_{index}",
                                UploadedBy = (int)model.RaisedBy,
                                PatientId = account.ReferenceId,
                                ContentType = file.ContentType,
                                Size = file.Length
                            };
                            document.DocumentUrl = await this.documentHelper.UploadAsync(file, guid, document.DocumentType, fileName);
                            document.ThumbnailUrl = this.documentHelper.GetThumbnail(file.ContentType);
                            patientDocuments.Add(document);
                            fileUrl = $@"{guid}/{document.DocumentUrl}";
                        }
                    }
                    else
                    {
                        var url = await this.documentHelper.UploadAttachmentsAsync(file, model.Mobile, "Others", fileName);
                        fileUrl = $@"{model.Mobile}/{url}";
                    }

                    var attachment = new Attachments
                    {
                        FileName = file.FileName,
                        Url = $@"{this.amazonS3Configuration.BucketURL}{fileUrl}",
                        Extension = System.IO.Path.GetExtension(file.FileName)?.Split(".")[1]
                    };

                    urls.Add(attachment);
                    index++;
                }

                if (patientDocuments.Count > 0)
                {
                    await this.patientDocumentServices.AddAsync(patientDocuments);
                }
            }

            if (urls.Count > 0)
            {
                model.Attachment = JsonConvert.SerializeObject(urls, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
            }

            var (ticketId, ticketNumber) = await this.ticketService.GenerateTicketAsync(model);

            if (ticketId <= 0)
            {
                return this.Success(ticketId);
            }

            try
            {
                var i = 0;
                var patientModel = await this.accountService.FindPatientByMobileAsync(model.Mobile);
                var getSupportUsers = await this.ticketService.GetSupportUsersAsync(model.Mobile);

                foreach (var item in getSupportUsers)
                {
                    if (patientModel != null)
                    {
                        if (i == 0)
                        {
                            item.RoleName = patientModel.FullName != null ? patientModel.FullName : null;
                            break;
                        }
                        i++;
                    }
                    else
                    {
                        item.RoleName = null;
                    }

                }
                await this.emailSender.SendAlertEmailToSupport(getSupportUsers);
            }
            catch (Exception)
            {
                // ignore
            }
            //var accountSessionSupportUsersModel = await this.accountSessionServices.FetchSupportDeviceTokenAsync();
            //var sessionSupportUserModel = accountSessionSupportUsersModel as AccountSessionModel[] ?? accountSessionSupportUsersModel.ToArray();
            //if (sessionSupportUserModel.Any())
            //{
            //    var deviceTokenForSupportAndroid = sessionSupportUserModel.Where(d => d.DeviceType == 2).Select(s => s.DeviceToken).ToList();
            //    if (deviceTokenForSupportAndroid.Any())
            //    {
            //        await this.pushNotificationHelper.SendAltAsync(
            //            "VirtualSteth",
            //            $@"Ticket Raised with Ticket Number : {ticketNumber}",
            //            "Virtual Steth Ticket Raised",
            //            deviceTokenForSupportAndroid,
            //            new List<string>(),
            //            null,
            //            (DateTime.Now.ToString()),
            //            null, null, null);
            //    }
            //}
            var response = await this.smsSender.SendTicketMessageAsync(model.Mobile, ticketNumber, model.CountryId);
            return this.Success(ticketNumber);
        }

        /// <summary>
        /// The fetch all async.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("fetch-all")]
        public async Task<ActionResult> FetchAllAsync([FromBody] TicketRequestFilter model, [FromHeader] LocationHeader header)
        {
            model = (TicketRequestFilter)EmptyFilter.Handler(model);

            model.LocationId = !string.IsNullOrEmpty(header.LocationId) ? int.Parse(header.LocationId) != 0 ? int.Parse(header.LocationId) : (int?)null : (int?)null;

            var json = JsonConvert.SerializeObject(model);
            var response = await this.ticketService.FetchAllTicketAsync(model.PageSize, model.PageIndex, model.AssignedTo, model.IsAdmin, model.AccountId, model.Priority, model.Status, model.StartDate, model.EndDate, model.IssueWith, model.MobileNo, model.DeviceType, model.AssigneeAccountId, model.LocationId);
            foreach (var item in response)
            {
                item.EncryptedTickedId = this.aesHelper.Encode(item.TicketId.ToString());
                try
                {
                    if (item.EndDate != null)
                    {
                        var totalHours = Convert.ToDateTime(item.EndDate).Subtract(item.CreatedDate).TotalHours.ToString("#.##");
                        var diff = Convert.ToDateTime(item.EndDate).Subtract(item.CreatedDate);
                        string output = string.Format("{0} days, {1} hours, {2} minutes, {3} seconds", diff.Days, diff.Hours, diff.Minutes, diff.Seconds);

                        item.Hours = $@"{output}";
                        item.HourComment = Convert.ToDateTime(item.DueDate).ToString("yyyy-MM-dd") == Convert.ToDateTime(item.EndDate).ToString("yyyy-MM-dd") ? "success" : "warning";

                        if (item.EndDate < Convert.ToDateTime(item.DueDateTime))
                        {
                            //item.Hours = $@" {Convert.ToDateTime(item.EndDate).Subtract(item.CreatedDate).TotalHours:#.##} hrs";
                            item.HourComment = double.Parse(Convert.ToDateTime(item.EndDate).Subtract(item.CreatedDate).TotalHours.ToString("#.##")) > 1 ? "danger" : "success";
                        }
                    }
                    else
                    {
                        if (DateTime.UtcNow > Convert.ToDateTime(item.DueDateTime))
                        {
                            var hours = DateTime.UtcNow.Subtract(Convert.ToDateTime(item.DueDate)).TotalHours.ToString("#.##");
                            var diff = Convert.ToDateTime(DateTime.UtcNow).Subtract(Convert.ToDateTime(item.DueDateTime));
                            string output = string.Format("{0} days, {1} hours, {2} minutes, {3} seconds", diff.Days, diff.Hours, diff.Minutes, diff.Seconds);

                            item.Hours = $@"{output}";
                            item.HourComment = double.Parse(hours) > 1 ? "danger" : "info";
                        }
                        else
                        {
                            var totalHours = DateTime.UtcNow.Subtract(item.CreatedDate).TotalHours.ToString("#.##");
                            var diff = Convert.ToDateTime(DateTime.UtcNow).Subtract(item.CreatedDate);
                            string output = string.Format("{0} days, {1} hours, {2} minutes, {3} seconds", diff.Days, diff.Hours, diff.Minutes, diff.Seconds);

                            if (string.IsNullOrEmpty(totalHours))
                            {
                                totalHours = "0";
                            }

                            item.Hours = $@"{output}";
                            item.HourComment = double.Parse(totalHours) > 1 ? "danger" : "info";
                        }
                    }
                }
                catch (Exception e)
                {
                    continue;
                }
            }

            return this.Success(response);
        }

        /// <summary>
        /// The get ticket details.
        /// </summary>
        /// <param name="encryptedTicketId">
        /// The ticket id.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpGet]
        [Authorize]
        [Route("get-ticket-details")]
        public async Task<ActionResult> GetTicketDetails(string encryptedTicketId)
        {
            if (string.IsNullOrEmpty(encryptedTicketId))
            {
                return this.BadRequest("Invalid ticket id.");
            }

            var id = long.Parse(this.aesHelper.Decode(encryptedTicketId));
            var response = await this.ticketService.GetTicketDetails(id);
            return this.Success(response ?? new TicketDetailsModel());
        }

        /// <summary>
        /// The get tickets count.
        /// </summary>
        /// <param name="encryptedId">
        /// The encrypted Id.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpGet]
        [Authorize]
        [Route("get-count")]
        public async Task<ActionResult> GetTicketsCount(string encryptedId)
        {
            var id = string.IsNullOrEmpty(encryptedId) ? (int?)null : int.Parse(encryptedId);
            var response = await this.ticketService.GetCount(id);
            return this.Success(response ?? new TicketCountModel());
        }

        /// <summary>
        /// The modify ticket.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("modify-ticket")]
        public async Task<ActionResult> ModifyTicket([FromBody] TicketDetailsModel model)
        {
            model = (TicketDetailsModel)EmptyFilter.Handler(model);
            var response = await this.ticketService.ModifyTicket(model);

            if (model.Status == "C")
            {
                await this.smsSender.SendTicketClosedMessageAsync(model.Mobile, model.TicketNumber, model.CountryId);
                var ticketDetails = await this.ticketService.GetTicketDetails(model.TicketId);
                var getSupportUsers = await this.ticketService.GetSupportUsersAsync(ticketDetails.Mobile);

                var ticket = new Models.MailTemplates.Tickets
                {
                    Description = ticketDetails.Description,
                    AssigneeName = ticketDetails.AssigneeName,
                    CreatedDate = ticketDetails.CreatedDate,
                    IssueWith = ticketDetails.IssueWith,
                    Mobile = ticketDetails.Mobile,
                    Priority = ticketDetails.Priority,
                    RaisedByName = ticketDetails.RaisedByName,
                    RaisedByRole = ticketDetails.RaisedByRole,
                    TicketNumber = ticketDetails.TicketNumber,
                    Status = ticketDetails.Status,
                    TicketOwner = ticketDetails.TicketOwner,
                    SupportUsers = getSupportUsers,
                    EmailType = "Closed"
                };
                await this.emailSender.SendAssignEmailToSupport(ticket);
            }

            return this.Success(response);
        }

        /// <summary>
        /// The assign ticket.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("assign-ticket")]
        public async Task<ActionResult> AssignTicket([FromBody] TicketTimelineModel model)
        {
            model = (TicketTimelineModel)EmptyFilter.Handler(model);
            var response = await this.ticketService.CreateTicketTimeline(model);
            return this.Success(response);
        }

        /// <summary>
        /// The get tickets count.
        /// </summary>
        /// <param name="encryptedTicketId">
        /// The encrypted ticket id.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpGet]
        [Authorize]
        [Route("get-ticket-timeline")]
        public async Task<ActionResult> GetTicketsTimeline(string encryptedTicketId)
        {
            var id = long.Parse(this.aesHelper.Decode(encryptedTicketId));
            var response = await this.ticketService.FetchTicketTimeLineAsync(id);
            return this.Success(response);
        }

        /// <summary>
        /// The update comments.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("update-ticket-comments")]
        public async Task<ActionResult> UpdateComments([FromBody] TicketRequestFilter model)
        {
            if (model.TicketTimelineId == null)
            {
                return this.BadRequest("TicketId is mandatory");
            }

            var response = await this.ticketService.UpdateTicketCommentsAsync((long)model.TicketTimelineId, model.Comments);
            return this.Success(response);
        }

        /// <summary>
        /// The add ticket owner.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("add-ticket-owner")]
        public async Task<ActionResult> AddTicketOwner([FromBody] TicketAssigneeModel model)
        {
            var json = JsonConvert.SerializeObject(model);
            model = (TicketAssigneeModel)EmptyFilter.Handler(model);
            var response = await this.ticketService.AddTicketOwnerAsync(model);
            var owner = await this.accountService.FindAsync((int)model.AccountId);
            var assigner = new UserAccount();
            if (model.CreatedBy > 0)
            {
                assigner = await this.accountService.FindAsync((int)model.CreatedBy);
            }
            var models = new TicketTimelineModel();
            switch (response)
            {
                case -2:
                    models.AssignedTo = (int)model.AccountId;
                    models.AssignedTouser = model.AssigneeAccountId;
                    models.TicketId = model.TicketId;
                    models.CreatedBy = (int)model.ModifiedBy;
                    models.Priority = "H";
                    models.IsAssigneeUserUpdate = true;
                    break;
                case -1:
                    return this.BadRequest("Something wrong ticket not updated");
                default:
                    models.AssignedTo = (int)model.AccountId;
                    models.AssignedTouser = model.AccountId;
                    models.TicketId = model.TicketId;
                    models.CreatedBy = (int)model.CreatedBy;
                    models.Priority = "H";
                    models.Description = $@"Ticket has been Intially assigned to {owner.FullName} by {assigner.FullName} on {DateTime.Now}";
                    break;
            }


            if (!string.IsNullOrEmpty(model.OwnerName))
            {
                await this.ticketService.UpdateTicketTimeline(models);
            }
            else
            {
                await this.ticketService.CreateTicketTimeline(models);
            }

            var ticketDetails = await this.ticketService.GetTicketDetails(model.TicketId);
            var getSupportUsers = await this.ticketService.GetSupportUsersAsync(ticketDetails.Mobile);

            var ticket = new Models.MailTemplates.Tickets
            {
                Description = ticketDetails.Description,
                AssigneeName = ticketDetails.AssigneeName,
                CreatedDate = ticketDetails.CreatedDate,
                IssueWith = ticketDetails.IssueWith,
                Mobile = ticketDetails.Mobile,
                Priority = ticketDetails.Priority,
                RaisedByName = ticketDetails.RaisedByName,
                RaisedByRole = ticketDetails.RaisedByRole,
                TicketNumber = ticketDetails.TicketNumber,
                Status = ticketDetails.Status,
                TicketOwner = ticketDetails.TicketOwner,
                SupportUsers = getSupportUsers,
                EmailType = "Assigned"
            };
            await this.emailSender.SendAssignEmailToSupport(ticket);
            return this.Success(response);
        }

        /// <summary>
        /// The get user performance async.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("get-performance")]
        public async Task<ActionResult> GetUserPerformanceAsync([FromBody] TicketRequestFilter model)
        {
            model = (TicketRequestFilter)EmptyFilter.Handler(model);
            string type = null;
            if (!string.IsNullOrEmpty(model.FilterType))
            {
                switch (model.FilterType)
                {
                    case "Today":
                        model.StartDate = DateTime.UtcNow;
                        type = "today";
                        break;
                    case "Yesterday":
                        model.StartDate = DateTime.UtcNow.AddDays(-1);
                        type = "other";
                        break;
                    default:
                        model.StartDate = DateTime.UtcNow.AddDays(-7);
                        type = "other";
                        break;
                }
            }

            var performanceTime = await this.ticketService.FetchPerformanceTime();

            if (performanceTime == null)
            {
                return this.BadRequest("Unable to calculate performance");
            }

            var tickets = await this.ticketService.GetTicketsAsync(model.StartDate, type, model.AccountId);

            var ticketModels = tickets.ToList();

            if (!ticketModels.Any())
            {
                return this.Success();
            }

            var ticketModel = new Performance
            {
                HighPriority = new PerformanceStatus(),
                LowPriority = new PerformanceStatus(),
                MediumPriority = new PerformanceStatus(),
                Tickets = new List<Tickets>()
            };

            foreach (var ticket in ticketModels)
            {
                var mod = new Tickets()
                {
                    EndDate = ticket.EndDate,
                    Status = ticket.Status,
                    StartDate = ticket.StartDate.ToString("yyyy-MM-dd"),
                    Priority = ticket.Priority,
                    EncryptedTicketId = this.aesHelper.Encode(ticket.TicketId.ToString()),
                    TicketNumber = ticket.TicketNumber
                };

                var totalTime = ticket.EndDate == null ? (DateTime.UtcNow - ticket.StartDate).TotalMinutes : ((DateTime)ticket.EndDate - ticket.StartDate).TotalMinutes;

                switch (ticket.Priority)
                {
                    case "H":
                        ticketModel.HighPriority.TotalHour += performanceTime.High;
                        ticketModel.HighPriority.TotalHourTaken += totalTime;
                        ticketModel.HighPriority.TicketCount += 1;
                        break;
                    case "L":
                        ticketModel.LowPriority.TotalHour += performanceTime.Low;
                        ticketModel.LowPriority.TotalHourTaken += totalTime;
                        ticketModel.LowPriority.TicketCount += 1;
                        break;
                    default:
                        ticketModel.MediumPriority.TotalHour += performanceTime.Medium;
                        ticketModel.MediumPriority.TotalHourTaken += totalTime;
                        ticketModel.MediumPriority.TicketCount += 1;
                        break;
                }

                ticketModel.Tickets.Add(mod);
            }

            if (ticketModel.HighPriority.TotalHourTaken > 0)
            {
                ticketModel.HighPriority.TotalAverage = double.Parse((ticketModel.HighPriority.TotalHourTaken
                                                        / (ticketModel.HighPriority.TotalHour / performanceTime.High)).ToString("#"));

                ticketModel.HighPriority.Performance = double.Parse((((ticketModel.HighPriority.TotalHour - ticketModel.HighPriority.TotalHourTaken)
                                                                      / ticketModel.HighPriority.TotalHour) * 100).ToString("#"));
            }

            if (ticketModel.MediumPriority.TotalHourTaken > 0)
            {
                ticketModel.MediumPriority.TotalAverage = double.Parse((ticketModel.MediumPriority.TotalHourTaken
                                                          / (ticketModel.MediumPriority.TotalHour / performanceTime.Medium)).ToString("#"));

                ticketModel.MediumPriority.Performance = double.Parse((((ticketModel.MediumPriority.TotalHour - ticketModel.MediumPriority.TotalHourTaken)
                                                                        / ticketModel.MediumPriority.TotalHour) * 100).ToString("#"));
            }

            if (ticketModel.LowPriority.TotalHourTaken > 0)
            {
                ticketModel.LowPriority.TotalAverage = double.Parse((ticketModel.LowPriority.TotalHourTaken
                                                       / (ticketModel.LowPriority.TotalHour / performanceTime.Low)).ToString("#"));

                ticketModel.LowPriority.Performance = double.Parse((((ticketModel.LowPriority.TotalHour - ticketModel.LowPriority.TotalHourTaken)
                                                       / ticketModel.LowPriority.TotalHour) * 100).ToString("#"));
            }

            return this.Success(ticketModel);
        }

        /// <summary>
        /// The add ticket owner.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("update-ticket-owner")]
        public async Task<ActionResult> UpdateTicketOwner([FromBody] TicketAssigneeModel model)
        {
            model = (TicketAssigneeModel)EmptyFilter.Handler(model);
            var ticketDetails = await this.ticketService.GetTicketDetails(model.TicketId);
            var response = await this.ticketService.UpdateTicketOwnerAsync(model);
            var models = new TicketTimelineModel();
            switch (response)
            {
                case -2:
                    models.AssignedTo = (int)model.AccountId;
                    models.AssignedTouser = model.AssigneeAccountId;
                    models.TicketId = model.TicketId;
                    models.CreatedBy = (int)model.ModifiedBy;
                    models.Priority = "H";
                    break;
                case -1:
                    return this.BadRequest("Something wrong ticket not updated");
            }


            if (!string.IsNullOrEmpty(model.OwnerName))
            {
                await this.ticketService.UpdateTicketTimeline(models);
            }

            var getSupportUsers = await this.ticketService.GetSupportUsersAsync(ticketDetails.Mobile);

            var ticket = new Models.MailTemplates.Tickets
            {
                Description = ticketDetails.Description,
                AssigneeName = ticketDetails.AssigneeName,
                CreatedDate = ticketDetails.CreatedDate,
                IssueWith = ticketDetails.IssueWith,
                Mobile = ticketDetails.Mobile,
                Priority = ticketDetails.Priority,
                RaisedByName = ticketDetails.RaisedByName,
                RaisedByRole = ticketDetails.RaisedByRole,
                TicketNumber = ticketDetails.TicketNumber,
                Status = ticketDetails.Status,
                TicketOwner = ticketDetails.TicketOwner,
                SupportUsers = getSupportUsers,
                EmailType = "Assigned"
            };
            await this.emailSender.SendAssignEmailToSupport(ticket);
            return this.Success(response);
        }
    }
}