using System;
using System.Web.Mvc;
using HMS.Class.BLL;
using HMS.Class.Helper;
using HMS.Models;

namespace HMS.Controllers
{
    /// <summary>
    /// Account controller class.
    /// </summary>
    public class AccountController : BaseController
    {
        #region Action Methods

        /// <summary>
        /// Login view action.
        /// </summary>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns>
        /// Returns login action result.
        /// </returns>
        public ActionResult Login(string returnUrl = "")
        {
            ViewBag.ReturnUrl = returnUrl;
            LoginModel model = new LoginModel();

            model.UserName = CommonLogic.GetCookieValue(StringConstants.RememberUserName);
            model.Password = CommonLogic.GetCookieValue(StringConstants.RememberPassword);

            if (!string.IsNullOrEmpty(model.UserName) && !string.IsNullOrEmpty(model.Password))
            {
                model.UserName = CommonLogic.Decrypt(model.UserName);
                model.Password = CommonLogic.Decrypt(model.Password);
                model.RememberMe = true;
            }

            return this.View(model);
        }

        /// <summary>
        /// Login view post action.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns>
        /// Returns login action result.
        /// </returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                UserModel loggedUser = UserBLL.ValidateLogin(model.UserName.Trim(), model.Password.Trim());

                if (loggedUser != null)
                {
                    if (loggedUser.UserId > 0)
                    {
                        CommonLogic.SetSessionValue(StringConstants.UserId, loggedUser.UserId);
                        CommonLogic.SetSessionValue(StringConstants.UserName, loggedUser.Email);
                        CommonLogic.SetSessionValue(StringConstants.FullName, loggedUser.FullName);
                        CommonLogic.SetSessionValue(StringConstants.RoleId, loggedUser.RoleId);
                        CommonLogic.SetSessionValue(StringConstants.RoleName, loggedUser.RoleName);
                        CommonLogic.SetSessionValue(StringConstants.CompanyId, loggedUser.CompanyId);
                        CommonLogic.SetSessionValue(StringConstants.ProfilePic, loggedUser.ProfilePic);

                        CommonLogic.SetSessionValue(StringConstants.CompanyName, "HMS Healthcare");
                        if(loggedUser.CompanyId > 0)
                        {
                            CompanyModel company = CompanyBLL.GetById(loggedUser.CompanyId.Value);
                            if(company != null)
                            {
                                CommonLogic.SetSessionValue(StringConstants.CompanyName, company.CompanyName);
                            }
                        }

                        LoginHistoryModel loginHistory = new LoginHistoryModel();
                        loginHistory.UserId = loggedUser.UserId;
                        loginHistory.Action = LoginHistoryAction.LogIn;
                        loginHistory.IPAddress = CommonLogic.GetClientIPAddress();

                        LoginHistoryBLL.SaveLoginHistory(loginHistory);

                        if (model.RememberMe)
                        {
                            CommonLogic.SetCookieValue(StringConstants.RememberUserName, CommonLogic.Encrypt(model.UserName), DateTime.Now.AddDays(StringConstants.RememberCookieExpiration));
                            CommonLogic.SetCookieValue(StringConstants.RememberPassword, CommonLogic.Encrypt(model.Password), DateTime.Now.AddDays(StringConstants.RememberCookieExpiration));
                        }
                        else
                        {
                            CommonLogic.ClearCookie(StringConstants.RememberUserName);
                            CommonLogic.ClearCookie(StringConstants.RememberPassword);
                        }

                        if (!string.IsNullOrEmpty(returnUrl))
                        {
                            return this.Redirect(returnUrl);
                        }
                        else
                        {
                            return this.RedirectToAction<SiteMapController>(dc => dc.Index());
                        }
                    }
                    else if (loggedUser.UserId == -1)
                    {
                        ViewBag.ErrorMsg = StringConstants.UserNotExist;
                    }
                    else if (loggedUser.UserId == -2)
                    {
                        ViewBag.ErrorMsg = StringConstants.UserNotActive;
                    }
                    else
                    {
                        ViewBag.ErrorMsg = StringConstants.UserLoginFailed;
                    }
                }
                else
                {
                    ViewBag.ErrorMsg = StringConstants.UserNotExist;
                }
            }

            return this.View(model);
        }

        /// <summary>
        /// Logout view action.
        /// </summary>
        /// <returns>
        /// Returns logout action result.
        /// </returns>
        public ActionResult Logout()
        {
            CommonLogic.SessionSignOut();
            return this.RedirectToAction<AccountController>(ac => ac.Login(string.Empty));
        }

        /// <summary>
        /// Forgot password view action.
        /// </summary>
        /// <returns>
        /// Returns forgot password action result.
        /// </returns>
        public ActionResult ForgotPassword()
        {
            return this.View(new ForgotPasswordModel());
        }

        /// <summary>
        /// Forgot password view post action.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns>
        /// Returns forgot password action result.
        /// </returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ForgotPassword(ForgotPasswordModel model)
        {
            try
            {
                UserModel userModel = UserBLL.GetByEmail(model.Email.Trim());

                if (userModel != null)
                {
                    EmailTemplateModel emailTemplate = EmailTemplateBLL.GetByCode("FORGOT_PASSWORD");

                    if (emailTemplate != null)
                    {
                        string mailBody = emailTemplate.Message;
                        mailBody = mailBody.Replace("##PASSWORD##", userModel.Password);
                        mailBody = mailBody.Replace("##SIGNATURE_NAME##", emailTemplate.Signature);

                        if (CommonLogic.SendMail(emailTemplate.FromEmail, userModel.Email, emailTemplate.Subject, mailBody, true))
                        {
                            this.ViewBag.SuccessMsg = StringConstants.PasswordSentMsg;
                            model.Email = string.Empty;
                        }
                        else
                        {
                            this.ViewBag.ErrorMsg = StringConstants.MailSendError;
                        }
                    }
                    else
                    {
                        this.ViewBag.ErrorMsg = string.Format(StringConstants.RecordNotExist, "Email Template");
                    }
                }
                else
                {
                    this.ViewBag.ErrorMsg = string.Format(StringConstants.RecordNotExist, "Email");
                }
            }
            catch (Exception ex)
            {
                this.ViewBag.ErrorMsg = CommonLogic.GetExceptionMessage(ex);
            }

            return this.View(model);
        }

        #endregion
    }
}
