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

namespace HMS.Controllers
{
    [LogOnAuthorize(Roles = "2,3,5")]
    public class MedicineController : 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, "Medicine");
            }

            ViewBag.PageNo = page ?? 1;
            ViewBag.PageSize = pageSize ?? MvcApplication.Setting.PageSize;
            ViewBag.SearchField = (string.IsNullOrEmpty(searchField) && !string.IsNullOrEmpty(searchValue)) ? "MedicineName" : searchField;
            ViewBag.SearchValue = searchValue;
            ViewBag.SortField = !string.IsNullOrEmpty(sortField) ? sortField : "MedicineName";
            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);
                    MedicineBLL.UpdateMultipleRecords(operationType, ids);
                }
                catch (Exception ex)
                {
                    return this.Json(new { IsError = true, ErrorMsg = CommonLogic.GetExceptionMessage(ex) });
                }
            }

      
            List<MedicineModel> medicineList = MedicineBLL.GetAll(ViewBag.SearchField, ViewBag.SearchValue, ViewBag.SortField, ViewBag.SortOrder, ViewBag.PageNo, ViewBag.PageSize);
            int totalRecords = 0;

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

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

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

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

            if (id.HasValue && id > 0)
            {
                ViewBag.Heading = "Edit Medicine";
                medicineVM.Medicine = MedicineBLL.GetById(id ?? 0);

                if (medicineVM.Medicine == null)
                {
                    medicineVM.Medicine = new MedicineModel();
                }
            }

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

        /// <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, MedicineViewModel model)
        {
            try
            {
                ViewBag.Heading = "Add Medicine";

                if (model.Medicine.MedicineId > 0)
                {
                    ViewBag.Heading = "Edit Medicine";
                }

                if (ModelState.IsValid)
                {
                    model.Medicine.CompanyId = SqlHelper.ParseNativeLong(CommonLogic.GetSessionValue(StringConstants.CompanyId));
                    model.Medicine.CreatedBy = SqlHelper.ParseNativeLong(CommonLogic.GetSessionValue(StringConstants.UserId));
                    //model.RoleId = RoleType.Patient.GetHashCode();

                    MedicineModel returnUser = MedicineBLL.Save(model.Medicine);

                    if (returnUser.MedicineId == -1)
                    {
                        ViewBag.ErrorMsg = string.Format(StringConstants.RecordAlreadyExist, returnUser.DuplicateColumn);
                    }
                    else if (returnUser.MedicineId == 0)
                    {
                        ViewBag.ErrorMsg = string.Format(StringConstants.RecordNotExist, returnUser.DuplicateColumn);
                    }
                }
            }
            catch (System.Exception ex)
            {
                ViewBag.ErrorMsg = CommonLogic.GetExceptionMessage(ex);
            }

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

        #endregion
    }
}
