using LHDN.CRM.BC.Common;
using LHDN.CRM.BC.Services;
using LHDN.CRM.Models.ViewModels;
using LHDN.CRM.WebAPI.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Results;

namespace LHDN.CRM.WebAPI.Controllers.Api
{
    [ApiErrorHandler]
    public class TaskApiController : BaseApiController
    {
        private TaskService svc = new BC.Services.TaskService();
        private EmailService emailSvc = new BC.Services.EmailService();
        private UserProfileService userSvc = new BC.Services.UserProfileService();
        private GeneralService generalSvc = new BC.Services.GeneralService();

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Cases.ViewCaseProfile,
            Constant.Authentication.Activity.ViewActivityProfile,
            Constant.Authentication.Cases.SearchCaseProfile,
            Constant.Authentication.Activity.SearchActivityProfile,
            Constant.Authentication.Task.CreateUpdateTask)]
        public IHttpActionResult GetCaseOrActivity(TaskPagedListViewModel paging)
        {
            int intCount = 0;
            TaskViewModel taskVM = svc.GetCaseOrActivity(paging, out intCount);
            DTResultViewModel<CaseForTaskViewModel> record = null;

            if (paging.Regarding == "Case")
            {
                DTResultViewModel<CaseForTaskViewModel> objRecord = null;
                objRecord = new DTResultViewModel<CaseForTaskViewModel>()
                {
                    draw = paging.Draw,
                    recordsTotal = intCount,
                    recordsFiltered = intCount,
                    data = taskVM.LstCase
                };
                return Json(objRecord);
            }
            else if (paging.Regarding == "Activity")
            {
                DTResultViewModel<ActForTaskViewModel> objRecord = null;
                objRecord = new DTResultViewModel<ActForTaskViewModel>()
                {
                    draw = paging.Draw,
                    recordsTotal = intCount,
                    recordsFiltered = intCount,
                    data = taskVM.LstActivity
                };
                return Json(objRecord);
            }
            return Json(record);
        }

        [HttpGet]
        public IHttpActionResult GetDropdown()
        {
            DropdownViewModel data = svc.GetDropdown();
            List<WorkflowUserViewModel> userLst = svc.GetAllUsers();

            return Json(new { data = data, users = userLst, currUser = userSvc.LoginID });
        }

        [HttpGet]
        [CRMAuthorize(Constant.Authentication.Task.SearchTask)]
        public IHttpActionResult GetTask(long id)
        {
            var data = svc.GetTask(id, userSvc.UserInfo);
            //if (data == null)
            //    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Task is deleted or not found!"));

            DateTime dtNow = DateTime.Now;

            AuditLogTxn(AuditService.AuditEventID.ViewTask,
                AuditService.ResultType.Success,
                AuditService.ActionType.View,
                userSvc.LoginID,
                dtNow,
                string.Format(Constant.AuditAdditionalInfo.Task, userSvc.DisplayName, userSvc.LoginID, id),
                null, "Task", id);

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Task.CreateUpdateTask)]
        public IHttpActionResult UpdateTask(TaskViewModel taskVM)
        {
            DataTable dTblResult = new DataTable();
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedName = userSvc.DisplayName;
            string strLastUpdatedEmail = userSvc.Email;
            DateTime dtNow = DateTime.Now;
            string strTaskDescription = "";
            string strTaskAlertDescription = "";
            bool blnAlertIsRead = false;
            long lngTaskID = 0;
            string strTaskRefNo = "";
            AuditService.ActionType actionType = new AuditService.ActionType();
            List<AuditDetailViewModel> lstAuditDetail = null;

            var data = svc.UpdateTask(taskVM, strLastUpdatedBy, dtNow, strLastUpdatedName, strLastUpdatedEmail, out lngTaskID, out strTaskRefNo);

            if (taskVM.TaskID > 0)
            {
                actionType = AuditService.ActionType.Update;
                lstAuditDetail = data.Select(a => new AuditDetailViewModel
                                {
                                    FieldName = a.DisplayName,
                                    OldValue = a.OldValue,
                                    NewValue = a.NewValue
                                }).ToArray().ToList();
                strTaskDescription = string.Format(Constant.RecentActivity.TaskUpdatedMsg, strTaskRefNo);
            }
            else
            {
                actionType = AuditService.ActionType.Add;
                strTaskDescription = string.Format(Constant.RecentActivity.TaskCreatedMsg, strTaskRefNo);
            }

            AuditLogTxn(AuditService.AuditEventID.CreateUpdateTask,
                    AuditService.ResultType.Success,
                    actionType,
                    userSvc.LoginID,
                    dtNow,
                    string.Format(Constant.AuditAdditionalInfo.Task, userSvc.DisplayName, userSvc.LoginID, lngTaskID),
                    lstAuditDetail,
                    "Task", lngTaskID);

            strTaskAlertDescription = string.Format(Constant.RecentActivity.TaskAlertForTask, strTaskRefNo);

            // Insert Recent Activity
            RecentActivityTxn("Task", lngTaskID, strTaskDescription, strLastUpdatedBy, strLastUpdatedName, dtNow, string.Format(Constant.RecentActivity.TaskURL, lngTaskID));

            var taskAlertDetail = generalSvc.GetTaskAlertDetail(taskVM.AssignToLogin, lngTaskID);
            if(taskAlertDetail == null)
            {
                //Insert Task Alert
                RecentTaskAlertNotify(taskVM.AssignToLogin, (Int16)(Constant.TableType.Task), lngTaskID, (int)(Constant.MessageType.New), strTaskAlertDescription, string.Format(Constant.RecentActivity.TaskURL, lngTaskID), blnAlertIsRead, strLastUpdatedBy, strLastUpdatedName, dtNow);
            }

            // Send email
            if (!string.IsNullOrEmpty(taskVM.AssignToEmail))
            {
                List<string> lstEmailTo = new List<string>();
                List<string> lstEmailCC = new List<string>();
                lstEmailTo.Add(taskVM.AssignToEmail);
                lstEmailCC.Add(strLastUpdatedEmail);
                emailSvc.SendEmailNotification(lstEmailTo, lstEmailCC, (int)Constant.EmailTemplate.TaskNotification, strLastUpdatedBy, lngTaskID, dtNow);
            }

            return Json(lngTaskID);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Task.DeleteTask)]
        public IHttpActionResult DeleteTask(TaskViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            DateTime dtNow = DateTime.Now;
            bool data = svc.DeleteTask(model);

            if (data)
            {
                AuditLogTxn(AuditService.AuditEventID.DeleteTask,
                AuditService.ResultType.Success,
                AuditService.ActionType.Delete,
                userSvc.LoginID,
                dtNow,
                string.Format(Constant.AuditAdditionalInfo.Task, userSvc.DisplayName, userSvc.LoginID, model.TaskID),
                null, "Task", model.TaskID);

                // Insert Recent Activity
                RecentActivityTxn("Task", model.TaskID, string.Format(Constant.RecentActivity.TaskDeletedMsg, model.TaskRefNo), strLastUpdatedBy, strLastUpdatedByName, dtNow, string.Format(Constant.RecentActivity.TaskURL, model.TaskID));
            }

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Constant.Authentication.Task.SearchTask)]
        public IHttpActionResult SearchTask(TaskPagedListViewModel paging)
        {
            int intCount = 0;

            if (paging.IsLinkfromDashboard)
            {
                paging.CurrentLoginID = userSvc.LoginID;
            }

            List<TaskViewModel> lst = svc.SearchTask(paging, out intCount);
            DTResultViewModel<TaskViewModel> objRecord = null;

            objRecord = new DTResultViewModel<TaskViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };

            AuditLogTxn(AuditService.AuditEventID.SearchTask,
                AuditService.ResultType.Success,
                AuditService.ActionType.View,
                userSvc.LoginID,
                DateTime.Now,
                "Search Task");

            return Json(objRecord);
        }

        [HttpPost]
        public IHttpActionResult ExportExcelSearchTask(ExportToExcelViewModel vm)
        {
            TaskPagedListViewModel paging = new TaskPagedListViewModel();
            paging = JsonConvert.DeserializeObject<TaskPagedListViewModel>(vm.strJSON);
            paging.Length = Convert.ToInt32(AdminService.ParameterSettings.Where(x => x.ParameterID == 22).FirstOrDefault().ParameterValue);

            byte[] bytFileContent = null;
            bytFileContent = svc.ExportExcelSearchTask(paging);

            ResponseMessageResult responseMessageResult = null;
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(bytFileContent)
            };

            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "CarianTugasan_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"
            };

            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            responseMessageResult = ResponseMessage(httpResponseMessage);

            return responseMessageResult;
        }

        [HttpPost]
        //[ValidateAjaxRequest]
        public IHttpActionResult GetDashboardMyTask(TaskPagedListViewModel paging)
        {
            int intCount = 0;
            List<TaskViewModel> lst = svc.GetDashboardMyTask(paging, userSvc.LoginID, out intCount);
            DTResultViewModel<TaskViewModel> objRecord = null;

            objRecord = new DTResultViewModel<TaskViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpPost]
        //[ValidateAjaxRequest]
        public IHttpActionResult GetDashboardMyTaskSubmission(TaskPagedListViewModel paging)
        {
            int intCount = 0;
            List<TaskViewModel> lst = svc.GetDashboardMyTaskSubmission(paging, userSvc.LoginID, out intCount);
            DTResultViewModel<TaskViewModel> objRecord = null;

            objRecord = new DTResultViewModel<TaskViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpPost]
        public IHttpActionResult GetLoginInfo()
        {
            UserInfoViewModel objUser = userSvc.GetUserByLoginID();

            return Json(objUser);
        }

        [HttpGet]
        //[ValidateAjaxRequest]
        public IHttpActionResult GetRecentActivity()
        {
            return Json(svc.GetRecentActivity(userSvc.LoginID));
        }


        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetPagedTaskListByID(TaskListPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetTaskListByID(paging, out intCount);
            DTResultViewModel<TaskListViewModel> objRecord = null;

            objRecord = new DTResultViewModel<TaskListViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount, //data.Count,
                recordsFiltered = intCount, //data.Count,
                data = lst
            };


            return Json(objRecord);
        }

        [HttpGet]
        public IHttpActionResult GetTaskForCalendar()
        {
            string strLoginID = userSvc.LoginID;
            var data = svc.GetTaskForCalendar(strLoginID);
            DateTime now = DateTime.Now;

            return Json(data);
        }
        
    }
}