using GreenTree.Nachtragsmanagement.Core;
using GreenTree.Nachtragsmanagement.Core.Authentication;
using GreenTree.Nachtragsmanagement.Services.Logging;
using GreenTree.Nachtragsmanagement.Services.User;
using GreenTree.Nachtragsmanagement.Web.Models.Login;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GreenTree.Nachtragsmanagement.Web.Controllers
{
    public class LoginController : Controller
    {
        private readonly IUserService _userService;
        private readonly IUserHelper _userHelper;
        private readonly ILogger _logger;

        public LoginController(
            IUserService userService,
            IUserHelper userHelper,
            ILogger logger)
        {
            _userService = userService;
            _userHelper = userHelper;
            _logger = logger;
        }

        // GET: Login
        public ActionResult Index()
        {
            var user = _userHelper.FromCookiesOrSession();

            if (user != null && user.Id != 0)
                return RedirectToAction("Index", "Home");

            return View("~/Views/Login/Index.cshtml");
        }

        [HttpPost]
        public ActionResult Index(LoginModel model)
        {
            var user = _userService.GetUserByCustomNumber(model.Username);

            try
            {
                if (user == null)
                {
                    ViewData["LoginFailed"] = true;

                    return Index();
                }

                var password = StaticHelper.GetMD5Hash(model.Password);

                if (!String.Equals(user.Password, password, StringComparison.InvariantCulture))
                {
                    ViewData["LoginFailed"] = true;

                    return Index();
                }

                user.CurrentRole = user.Roles.First(r1 => r1.Level == user.Roles.Max(r2 => r2.Level));

                if (model.IsPermanent.HasValue && model.IsPermanent.Value)
                    _userHelper.ToCookiesAndSession(user, DateTime.Now.AddYears(1));
                else
                    _userHelper.ToCookiesAndSession(user, DateTime.Now.AddHours(8));

                _logger.Debug(
                    String.Format("Login für Benutzer \"{0}\" erfolgreich.", model.Username));

                return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                _logger.Error("Fehler bei Login eines Benutzers.", ex, user);

                throw;
            }
        }

        public ActionResult Logout()
        {
            _userHelper.ClearCookieAndSession();

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