using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Infrastructure.DataAccess;
using TestCasePlanner.Infrastructure;
using Infrastructure.Models;
using TestCasePlanner.Models.ViewModels;

namespace TestCasePlanner.Controllers
{
    [RoutePrefix("manage/users")]
    public class UserController : AppBaseController
    {
        public UserController() 
            : this(new UserManager<AppUser>(new UserStore<AppUser>(new AppDbContext())), new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new AppDbContext())))
        {
        }

        public UserController(UserManager<AppUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            RoleManager = roleManager;
            UserManager = userManager;
        }

        public UserManager<AppUser> UserManager { get; private set; }
        public RoleManager<IdentityRole> RoleManager { get; private set; }

        // GET: /manage/users
        [Route("")]
        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {
            var users = UserManager.Users;
            var model = new List<UserViewModel>();
            foreach (var user in users)
            {
                var userModel = new UserViewModel { UserName = user.UserName, Email = user.Email, Role = UserManager.GetRoles(user.Id).First() };
                model.Add(userModel);
            }
            return View(model);
        }

        // GET: /login
        [AllowAnonymous]
        [Route("~/login")]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        // POST: /login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [Route("~/login")]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // GET: /manage/users/create
        [Authorize(Roles = "Admin")]
        public ActionResult Create()
        {
            var roles = RoleManager.Roles.Select(r => new SelectListItem { Value = r.Name, Text = r.Name });
            var model = new RegisterViewModel { Roles = new SelectList(roles, "Value", "Text")};
            return View(model);
        }

        // POST: /manage/users/create
        [HttpPost]
        [Authorize(Roles = "Admin")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser() { UserName = model.UserName, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                
                if (result.Succeeded)
                {
                    result = await UserManager.AddToRoleAsync(user.Id, model.SelectedRoleId);

                    if (result.Succeeded)
                    { 
                        // await SignInAsync(user, isPersistent: false);
                        return RedirectToAction("Index", "User");
                    }
                }
                else
                {
                    AddErrors(result);
                }
            }

            var roles = RoleManager.Roles.Select(r => new SelectListItem { Value = r.Name, Text = r.Name });
            model = new RegisterViewModel { Roles = new SelectList(roles, "Value", "Text") };
            return View(model);
        }

        // GET: /preferences
        [Route("~/preferences")]
        [Authorize]
        public ActionResult Manage(ManageMessageId? message)
        {
            if (message == ManageMessageId.ChangePasswordSuccess)
            {
                ViewBag.StatusMessage = Resources.Resources.PasswordChanged;
                ViewBag.Status = 1;
            }
            else
            {
                ViewBag.StatusMessage = string.Empty;
            }

            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        // POST: /preferences
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize]
        [Route("~/preferences")]
        public async Task<ActionResult> Manage(ManageUserViewModel model)
        {
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (ModelState.IsValid)
            {
                var userId = User.Identity.GetUserId();
                IdentityResult result = await UserManager.ChangePasswordAsync(userId, model.OldPassword, model.NewPassword);
                if (result.Succeeded)
                {
                    return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                }
                else
                {
                    AddErrors(result);
                    ViewBag.StatusMessage = Resources.Resources.PasswordChangeError;
                    ViewBag.Status = 0;
                }
            }

            // else redisplay form with errors
            return View(model);
        }

        // GET
        // Changes the language of application
        public ActionResult SelectLanguage(string language)
        {
            // language = LanguageHelper.GetImplementedCulture(language);

            HttpCookie cookie = Request.Cookies["TestCasePlanner-SelectedLanguage"];
            if (cookie != null)
                cookie.Value = language;   // update cookie value
            else
            {
                cookie = new HttpCookie("TestCasePlanner-SelectedLanguage");
                cookie.Value = language;
                cookie.Expires = DateTime.Now.AddYears(1);
            }
            Response.Cookies.Add(cookie);
            return RedirectToAction("Manage");
        }

        // POST: /logout
        [HttpPost]
        [Route("~/logout")]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            AuthenticationManager.SignOut();
            return RedirectToAction("Index", "Dashboard");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && UserManager != null)
            {
                UserManager.Dispose();
                UserManager = null;
            }
            base.Dispose(disposing);
        }

        #region Helpers

        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

        private async Task SignInAsync(AppUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }

        private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
        }

        private bool HasPassword()
        {
            var user = UserManager.FindById(User.Identity.GetUserId());
            if (user != null)
            {
                return user.PasswordHash != null;
            }
            return false;
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            Error
        }

        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Dashboard");
            }
        }

        #endregion
    }
}