using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

using BeWo.Data;
using BeWoPlanerMobil.Service;
using BS.Shared;
using BS.Shared.DataContracts;

namespace BeWoPlanerMobil.Controllers
{
    public class LoginController : AbstractBaseController
    {
		private const string loginErrorIndex = "LoginErrorIndex";

		[HttpPost]
		public ActionResult Index()
		{

			ViewData[loginErrorIndex] = string.Empty;

			if (MobileSessionFacade.IsUserLoggedIn())
			{
				log.Info(string.Format("LoginController.Index(): Loggedin User: {0}", MobileSessionFacade.LoggedInUser.LoginName));

				if (!MobileSessionFacade.LoggedInUser.UserGroups.Any(a => a.Rights.Any(f => f.RightType.Equals(UserRightType.ServiceRecordView_View))) &&
					!MobileSessionFacade.LoggedInUser.UserGroups.Any(a => a.Rights.Any(f => f.RightType.Equals(UserRightType.ViewAll))))
				{
					ViewData[loginErrorIndex] = HttpUtility.HtmlDecode("Sie haben keine ausreichenden Berechtigungen, um die Zeiterfassung anzeigen zu lassen.");
					return View("Index");
				}

				FormsAuthentication.SetAuthCookie(MobileSessionFacade.LoggedInUser.LoginName, true);
				ViewData[loginErrorIndex] = string.Empty;

				var keks = new HttpCookie("tenantKeks") {Value = MobileSessionFacade.Tenant, Expires = DateTime.Now.AddDays(1)};
				HttpContext.Response.SetCookie(keks);

				var brauser = Request.Browser;
				var brauserInfoDC = new BeWoMobilBrowserInfoDC
				{
					Type = brauser.Type,
					Name = brauser.Browser,
					BrowserVersion = brauser.Version,
					Platform = brauser.Platform,
					Tenant = SessionFacade.Tenant
				};

				OperationsService.InsertBeWoMobilBrowserInfo(brauserInfoDC);

				return RedirectToActionPermanent("Main", "Main");
			}
			log.Info(String.Format("LoginController.Index(): Login failed! Tenant = {0}", SessionFacade.Tenant));

			ViewData[loginErrorIndex] = "Die Anmeldung ist fehlgeschlagen. Bitte überprüfen Sie Benutzername und Passwort.";
			return View("Index");
		}

	    public ActionResult Index(string tenant, string returnUrl)
	    {
		    if (returnUrl != null)
		    {
			    return RedirectToAction("Index", new {tenant = MobileSessionFacade.Tenant});
		    }

		    if (tenant == null && returnUrl == null)
		    {
				var keks = HttpContext.Request.Cookies.Get("tenantKeks");
				if(keks != null)
					tenant = keks.Value;
		    }

			if (MobileSessionFacade.IsUserLoggedIn())
				return RedirectToActionPermanent("Main", "Main");

			SessionFacade.Tenant = tenant;
		    return View("Index");
	    }
    }
}
