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

using Tools.Users;
using web_map.Models;

namespace web_map.Controllers
{
    public class AccountController : BaseController
    {
        UserContext userContext = UserContext.Get();


        [HttpGet]
        public ActionResult Index()
        {
            //if (User.Identity.IsAuthenticated)
            //    ViewBag.User = User.Identity.Name;
            //else
            //    ViewBag.User = "NoAuth";

            return View();
        }


        [HttpGet]
        public ActionResult Login()
        {
            if (User.Identity.IsAuthenticated)
                Redirect("/Home/Index");
                //RedirectToAction("Index");

            return View(new AuthModel());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(AuthModel model)
        {
            var WhereToGo = RequestUrl();
            if (User.Identity.IsAuthenticated)
                return Redirect("/Home/Index");
                //RedirectToAction("Index");

            // поиск пользователя в бд
            var user = userContext.Users.
                FirstOrDefault(e => e.Login == model.Login
                && e.Password == model.Password);

            if (user != null)
            {
                if (!user.IsAuth)
                {
                    FormsAuthentication.SetAuthCookie(user.Login, true);
                    user.IsAuth = true;
                    if (WhereToGo != "/Account/Login")
                        return Redirect(WhereToGo);
                    else
                        return Redirect("/Home/Index");
                    //RedirectToAction("Index");
                }
                else
                {
                    return View(new AuthModel
                    {
                        AuthError = true,
                        ErrorMsg = "Пользователь уже авторизован"
                    });
                }
            }
            else
            {
                return View(new AuthModel
                {
                    AuthError = true,
                    ErrorMsg = "Пользователя с таким логином и паролем нет"
                });
            }

        }


        [HttpGet]
        public ActionResult Logoff()
        {
            if (User.Identity.IsAuthenticated)
            {
                // поиск пользователя в бд
                var user = userContext.Users.
                    FirstOrDefault(e => e.Login == User.Identity.Name);

                if (user != null)
                    user.IsAuth = false;
            }

            FormsAuthentication.SignOut();
            return Redirect(RequestUrl());
            //RedirectToAction("Index");
        }

    }
}