using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BeWo.Data.Entities;
using BeWo.Service.DCEntityMapper;
using BeWo.Service.ServiceContracts;
using BeWo.Service.ServiceImplementations;
using BS.Shared;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;

namespace BeWoPlanerAndroid.Service
{
    public class MobileSessionFacade
    {
        public MobileSessionFacade()
        {
            CustomerService   = new CustomerServiceImp();
            EmployeeService   = new EmployeeServiceImp();
            OperationsService = new OperationsServiceImp();
            ResourceService   = new ResourceServiceImp();
            AnalysisService   = new AnalysisServiceImp();
            ValueListService  = new ValueListServiceImp();
            UserService       = new UserServiceImp();
        }

        public ICustomerService   CustomerService   { get; private set; }
        public IEmployeeService   EmployeeService   { get; private set; }
        public IOperationsService OperationsService { get; private set; }
        public IValueListService  ValueListService  { get; private set; }
        public ResourceServiceImp ResourceService   { get; private set; }
        public IAnalysisService   AnalysisService   { get; private set; }
        public IUserService       UserService       { get; private set; }

        public static ApplicationUser LoggedInUser
        {
            get { return HttpContext.Current.Session["apuser"] as ApplicationUser; }

            set
            {
                HttpContext.Current.Session["apuser"] = value;
                EmployeeFullname = value != null ? value.Employee.Person.FirstNameLastName : string.Empty;
            }
        }

        public static string EmployeeFullname { get; set; }

        public static EmployeeDC LoggedInEmployee
        {
            get { return LoggedInUser == null ? null : MapperFactory.EmployeeDC_Employee.MapToNewDC(LoggedInUser.Employee); }
        }

        public static CompactEmployeeDC LoggedInCompactEmployee
        {
            get { return LoggedInUser == null ? null : MapperFactory.CompactEmployeeDC_Employee.MapToNewDC(LoggedInUser.Employee); }
        }

        public static string Tenant
        {
            get { return HttpContext.Current.Session["tenant"] as string; }

            set { HttpContext.Current.Session["tenant"] = value; }
        }

        public static bool IsUserLoggedIn()
        {
            return LoggedInUser != null;
        }

        public static void LogUserOut()
        {
            HttpContext.Current.Session["apuser"] = null;
            HttpContext.Current.Session.Abandon();
        }

        public static bool CheckForUserRight(UserRightType userRightType)
        {
            return LoggedInUser != null && LoggedInUser.UserGroups.Any(ug => ug.Rights.Any(rr => rr.RightType.Equals(userRightType)));
        }
    }
}