using System.Web.Mvc;
using Qusion.Cms.Users.Core;
using Qusion.Cms.Users.Domain;
using Qusion.WebApp.Areas.Qusion.Filters;
using Qusion.WebApp.Areas.Qusion.Mailers.Account;
using Qusion.WebApp.Areas.Qusion.Models.Account;
using WebMatrix.WebData;

namespace Qusion.WebApp.Areas.Qusion.Controllers
{
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {
        private readonly UserService _userService;

        public AccountController(UserService userService)
        {
            _userService = userService;
        }

        [QusionAuthorize(LoginPage = "/qusion/account/login")]/*REDIREKCIJA NA  APP*/
        public ActionResult Index(string returnUrl)
        {
            return RedirectToAction("Index", "App");
        }

        //
        // GET: /Qusion/Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Qusion/Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                User user = _userService.Get(model.Email);
                if (user != null && user.Locked)
                {
                    ModelState.AddModelError("", "User is locked.");
                    return View(model);
                }

                if(user != null && user.Deactived)
                {
                    ModelState.AddModelError("", "This account is deleted.");
                    return View(model);
                }

                if (WebSecurity.Login(model.Email, model.Password,  model.RememberMe))
                    return RedirectToLocal("/Qusion/App/");
            }


            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The email or password provided is incorrect.");
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult ActiveAccount(string token)
        {
            ViewBag.Actived = false;
            return View(new ActiveAccountModel { Token = token });
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ActiveAccount(ActiveAccountModel model)
        {
            if(ModelState.IsValid)
            {
                if (WebSecurity.ConfirmAccount(model.Token))
                    ViewBag.Actived = true;
                else
                    ModelState.AddModelError("", "Your token is not valid!");
            }
            return View(model);
        }

        //
        // GET: /Qusion/Account/ForgotPassword

        [AllowAnonymous]
        public ActionResult ForgotPassword(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        

        //
        // POST: /Qusion/Account/ForgotPassword

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ForgotPassword(ForgotPasswordModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.UserExists(model.Email))
            {
                string token = WebSecurity.GeneratePasswordResetToken(model.Email);
                var mail = new PasswordResetMailerModel
                               {
                                   Email = model.Email,
                                   Token = token
                               };
                // send password reset token
                new AccountMailer().PasswordReset(mail).Send();
                return RedirectToAction("ResetPassword");
            }
            ModelState.AddModelError("", "Email you provided doesn't exists in our system.");
            return View(model);
        }

        //
        // GET: /Qusion/Account/ForgotPassword

        [AllowAnonymous]
        public ActionResult ResetPassword(string token)
        {
            ViewBag.Reset = false;
            return View(new ResetPasswordModel {Token = token});
        }

        //
        // POST: /Qusion/Account/ForgotPassword

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ResetPassword(ResetPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                int username = WebSecurity.GetUserIdFromPasswordResetToken(model.Token);
                if (username > -1)
                {
                    WebSecurity.ResetPassword(model.Token, model.Password);
                    ViewBag.Reset = true;
                    return View(model);
                }
            }
            ViewBag.Reset = false;
            ModelState.AddModelError("", "You have provided an invalid token.");
            return View(model);
        }


        //
        // GET: /Qusion/Account/LogOff
        [QusionAuthorize(LoginPage = "/qusion/account/login")]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Login", "Account");
        }

        #region Helper methods

        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
                return Redirect(returnUrl);

            return RedirectToAction("Index", "App");
        }

        #endregion
    }
}