using BookingJieFeng.DB;
using BookingJieFeng.DB.Model;
using BookingJieFeng.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Web.Security;

namespace BookingJieFeng.Controllers
{
    public class BaseController : Controller
    {
        private BookingDB bookingDB = new BookingDB();

        protected CurrentUser CurrentUser
        {
            get
            {
                if (Session["UserInfo"] != null)
                {
                    return (CurrentUser)Session["UserInfo"];
                }

                return null;
            }
        }

        protected CurrentCompany CurrentCompany
        {
            get
            {
                if (Session["CompanyInfo"] != null)
                {
                    return (CurrentCompany)Session["CompanyInfo"];
                }

                return null;
            }
        }

        protected void InitCurrentUser(SysUser user)
        {
            Session["UserInfo"] = user.AsCurrentUser();
        }

        protected void InitCurrentCompany(SysUser user)
        {
            Session["CompanyInfo"] = user.AsCurrentCompany();
        }

        protected override void OnAuthentication(AuthenticationContext filterContext)
        {
            base.OnAuthentication(filterContext);

            if (Session["UserInfo"] == null)
            {
                if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
                     && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
                {
                    filterContext.Result = new RedirectResult(Url.Action("login", "user", new { returnUrl = Request.Url }));
                }
            }
        }

        protected bool ValidData(out string message)
        {
            if (!ModelState.IsValid)
            {
                StringBuilder errStr = new StringBuilder();
                foreach (var sta in ModelState.Values)
                {
                    if (sta.Errors.Count > 0)
                    {
                        foreach (var err in sta.Errors)
                        {
                            errStr.AppendLine(err.ErrorMessage);
                        }
                    }
                }

                message = errStr.ToString();
                return false;
            }
            else
            {
                message = string.Empty;
                return true;
            }
        }
    }
}