using System;
using System.Security.Principal;
using System.Threading;
using System.Web.Mvc;
using System.Web.Security;
using TelerikMVC3Test.Models;

namespace TelerikMVC3Test.Controllers
{
    public class AccountController : Controller
    {
        public ViewResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if(ModelState.IsValid)
            {
                var now = DateTime.Now;
                var ticket = new FormsAuthenticationTicket(2, model.UserName, now, now.AddSeconds(600), model.RememberMe, null);
                var encryptedTicket = FormsAuthentication.Encrypt(ticket);
                var cookie = FormsAuthentication.GetAuthCookie(FormsAuthentication.FormsCookieName, false);
                cookie.Value = encryptedTicket;
                cookie.HttpOnly = true;
                
                var identity = new FormsIdentity(ticket);
                HttpContext.User = Thread.CurrentPrincipal = new GenericPrincipal(identity, new String[] { "Admin" });

                FormsAuthentication.SetAuthCookie(model.UserName, true);
                return RedirectToAction("Index", "Home");
            }
            return View(model);
        }
    }
}
