using System;
using System.Web.Mvc;
using Wierszowki.Core.Interfaces;
using Wierszowki.Core.Linq;
using Wierszowki.Models;
using Wierszowki.Models.Interfaces;

namespace Wierszowki.Controllers
{
    public class AccountController : Controller
    {
        private readonly IRepository<User> _repository;

        public IFormsAuthentication FormsAuth
        {
            get;
            private set;
        }

        public AccountController()
        {
            _repository = new LinqRepository<User>();
            FormsAuth = new FormsAuthenticationService();
        }

        public AccountController(IFormsAuthentication formsAuth, IRepository<User> repository)
        {
            _repository = repository;
            FormsAuth = formsAuth ?? new FormsAuthenticationService();
        }

        public ActionResult Login()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string login, string password, bool rememberMe, string returnUrl)
        {
            if (!ValidateLogOn(login, password))
                return View();

            FormsAuth.SignIn(login, rememberMe);
            
            if (!String.IsNullOrEmpty(returnUrl))
                return Redirect(returnUrl);
            
            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOff()
        {
            FormsAuth.SignOut();
            return RedirectToAction("Index", "Home");
        }

        private bool ValidateLogOn(string login, string password)
        {
            if (string.IsNullOrEmpty(login))
                ModelState.AddModelError("username", "Proszę podać login.");
            if (string.IsNullOrEmpty(password))
                ModelState.AddModelError("password", "Proszę podać hasło.");

            if (ModelState.IsValid)
            {
                if (!_repository.Exists(u => u.Login == login && u.Password == password))
                    ModelState.AddModelError("_FORM", "Podano nieprawidłowy login lub hasło.");
            }
            return ModelState.IsValid;
        }
    }
}