using System;
using System.Collections.Generic;
using System.Web.Mvc;
using HMS.Class.BLL;
using HMS.Class.Helper;
using HMS.Models;
using HMS.ViewModel;
using System.Web;
using System.IO;
using System.Linq;

namespace HMS.Controllers
{
    [LogOnAuthorize(Roles = "2,3,4")]
    public class DeathController : BaseController
    {
        #region Action Methods

        /// <summary>
        /// Index view action.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <param name="searchField">The search field.</param>
        /// <param name="searchValue">The search value.</param>
        /// <param name="sortField">The sort field.</param>
        /// <param name="sortOrder">The sort order.</param>
        /// <returns>
        /// Returns index action result.
        /// </returns>
        public ActionResult Index(int? page, int? pageSize, string searchField, string searchValue, string sortField, string sortOrder)
        {
            if (CommonLogic.GetQueryString("status").Equals("s", StringComparison.CurrentCultureIgnoreCase))
            {
                ViewBag.SuccessMsg = string.Format(StringConstants.RecordSave, "Death Report");
            }

            ViewBag.PageNo = page ?? 1;
            ViewBag.PageSize = pageSize ?? MvcApplication.Setting.PageSize;
            ViewBag.SearchField = (string.IsNullOrEmpty(searchField) && !string.IsNullOrEmpty(searchValue)) ? "PatientId" : searchField;
            ViewBag.SearchValue = searchValue;
            ViewBag.SortField = !string.IsNullOrEmpty(sortField) ? sortField : "PatientId";
            ViewBag.SortOrder = !string.IsNullOrEmpty(sortOrder) ? sortOrder : "ASC";

            string mode = CommonLogic.GetFormDataString("mode");
            string ids = CommonLogic.GetFormDataString("ids");

            if (!string.IsNullOrEmpty(mode) && !string.IsNullOrEmpty(ids))
            {
                try
                {
                    MultiOperationType operationType = (MultiOperationType)Enum.Parse(typeof(MultiOperationType), mode, true);
                    ReportBLL.UpdateMultipleRecords(operationType, ids);
                }
                catch (Exception ex)
                {
                    return this.Json(new { IsError = true, ErrorMsg = CommonLogic.GetExceptionMessage(ex) });
                }
            }


            List<ReportModel> list = ReportBLL.GetAllDeathReport(ViewBag.SearchField, ViewBag.SearchValue, ViewBag.SortField, ViewBag.SortOrder, ViewBag.PageNo, ViewBag.PageSize);
            int totalRecords = 0;

            if (list != null && list.Count > 0)
            {
                totalRecords = list[0].TotalRecordCount;
            }

            ViewBag.ListRecords = list.Count;
            ViewBag.PagedList = list.ToStaticPagedList((int)ViewBag.PageNo, (int)ViewBag.PageSize, totalRecords);

            return Request.IsAjaxRequest() ? (ActionResult)PartialView("Index", list) : this.View(list);
        }

        /// <summary>
        /// Add view action.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns>
        /// Returns add action result.
        /// </returns>
        public ActionResult Add(long? id)
        {
            var reportVM = new ReportViewModel();
            ViewBag.Heading = "Add Death Report";

            if (id.HasValue && id > 0)
            {
                ViewBag.Heading = "Edit Death Report";
                reportVM.Report = ReportBLL.GetById(id ?? 0);

                if (reportVM.Report == null)
                {
                    reportVM.Report = new ReportModel();
                }
                else
                {
                    if (!string.IsNullOrEmpty(reportVM.Report.ReportFile))
                    {
                        string path = CommonLogic.GetConfigValue(StringConstants.AppConfig_ReportDocFolderPath);
                        string physicalPath = Path.Combine(Server.MapPath(path), "Death",Convert.ToString(reportVM.Report.CompanyId), reportVM.Report.ReportFile);
                        if (System.IO.File.Exists(physicalPath))
                        {
                            reportVM.Report.ReportFile = Path.Combine(path, "Death",Convert.ToString(reportVM.Report.CompanyId), reportVM.Report.ReportFile);
                        }
                        else
                        {
                            reportVM.Report.ReportFile = "";
                        }
                    }
                    else
                    {
                        reportVM.Report.ReportFile = "";
                    }
                }

            }

            return Request.IsAjaxRequest() ? (ActionResult)PartialView("Add", reportVM) : this.View(reportVM);
        }

        /// <summary>
        /// Add view post action.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="model">The model.</param>
        /// <returns>
        /// Returns add action result.
        /// </returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Add(long? id, ReportViewModel model, HttpPostedFileBase ReportDoc)
        {
            try
            {
                ViewBag.Heading = "Add Death Report";

                if (model.Report.ReportId > 0)
                {
                    ViewBag.Heading = "Edit Death Report";
                }

                if (ModelState.IsValid)
                {
                    model.Report.CompanyId = SqlHelper.ParseNativeLong(CommonLogic.GetSessionValue(StringConstants.CompanyId));
                    model.Report.CreatedBy = SqlHelper.ParseNativeLong(CommonLogic.GetSessionValue(StringConstants.UserId));
                    model.Report.ReportTypeId = ReportType.Death.GetHashCode();

                    string path = Path.Combine(Server.MapPath(CommonLogic.GetConfigValue(StringConstants.AppConfig_ReportDocFolderPath)), "Death", Convert.ToString(model.Report.CompanyId));

                    if (ReportDoc != null && ReportDoc.ContentLength > 0)
                    {
                        try
                        {
                            int MaxContentLength = CommonLogic.GetConfigIntValue(StringConstants.AppConfig_ReportDocMaxSize);
                            string[] AllowedFileExtensions = CommonLogic.GetConfigValue(StringConstants.AppConfig_ReportDocAllowedFileType).Split(',');

                            string fileName = Path.GetFileNameWithoutExtension(ReportDoc.FileName);
                            string fileExtension = Path.GetExtension(ReportDoc.FileName);

                            if (!AllowedFileExtensions.Contains(fileExtension))
                            {
                                ModelState.AddModelError("Report.ReportFile", string.Format(StringConstants.ValidFileTypeMsg, string.Join(", ", AllowedFileExtensions)));
                                return this.View(model);
                            }
                            else if (ReportDoc.ContentLength > MaxContentLength)
                            {
                                ModelState.AddModelError("Report.ReportFile", string.Format(StringConstants.ValidFileSizeMsg, MaxContentLength / 1024.0));
                                return this.View(model);
                            }
                            else
                            {
                                fileName = string.Concat(DateTime.Now.ToString("yyyyMMddHHmmss"), fileExtension);

                                if (!Directory.Exists(path))
                                {
                                    Directory.CreateDirectory(path);
                                }

                                path = Path.Combine(path, fileName);

                                model.Report.ReportFile = fileName;

                                ReportDoc.SaveAs(path);
                            }
                        }
                        catch
                        {
                        }
                    }

                    ReportModel returnRecord = ReportBLL.Save(model.Report);

                    if (returnRecord.ReportId == -1)
                    {
                        ViewBag.ErrorMsg = string.Format(StringConstants.RecordAlreadyExist, returnRecord.DuplicateColumn);
                    }
                    else if (returnRecord.ReportId == 0)
                    {
                        ViewBag.ErrorMsg = string.Format(StringConstants.RecordNotExist, returnRecord.DuplicateColumn);
                    }
                    else
                    {
                        

                        return RedirectToAction("Index", routeValues: new { status = "s" });
                    }
                }
            }
            catch (System.Exception ex)
            {
                ViewBag.ErrorMsg = CommonLogic.GetExceptionMessage(ex);
            }

            return Request.IsAjaxRequest() ? (ActionResult)PartialView("Add", model) : this.View(model);
        }

        #endregion
    }
}
