using System;
using System.Dynamic;
using Nancy;
using Nancy.Authentication.Forms;
using Nancy.Extensions;

namespace RaceLapTimer.Modules
{
    public class LoginModule:NancyModule
    {
        public LoginModule()
        {
            Get["/login"] = args => GetLoginPage();

            Post["/login"] = args => PostLoginAttempt();

            Get["/logout"] = args => {
                return this.LogoutAndRedirect("~/");
            };
        }

        private dynamic GetLoginPage()
        {
            dynamic model = new ExpandoObject();
            model.Errored = Request.Query.error.HasValue;

            return View["login", model];
        }

        private dynamic PostLoginAttempt()
        {
            var userGuid = UserDatabase.ValidateUser((string)Request.Form.Username,
                    (string)Request.Form.Password);

            if (userGuid == null)
            {
                return Context.GetRedirect("~/login?error=true&username=" + (string)Request.Form.Username);
            }

            DateTime? expiry = null;
            if (Request.Form.RememberMe.HasValue)
            {
                expiry = DateTime.Now.AddDays(7);
            }

            return this.LoginAndRedirect(userGuid.Value, expiry);
        }
    }
}
