using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using IronIntel.Services;
using IronIntel.Services.Users;
using IronIntel.Site;
using IronIntel.Contractor.Users;
using IronIntel.Services.Customers;
using System.Web;
using Foresight.Fleet.Services;

namespace IronIntel.Contractor.Site
{
    public class ContractorBasePage : IronIntelBasePage
    {
        public static string AppVersion
        {
            get
            {
                return SystemParams.AppVersion;
            }
        }

        new public string PageTitle
        {
            get
            {
                if (MainStyleObj != null && !string.IsNullOrWhiteSpace(MainStyleObj.PageTitle))
                    return MainStyleObj.PageTitle;
                return base.PageTitle;
            }
        }

        private MainStyle _MainStyleObj;
        protected MainStyle MainStyleObj
        {
            get
            {
                if (_MainStyleObj == null)
                {
                    _MainStyleObj = SystemParams.GetMainStyle();
                }
                return _MainStyleObj;
            }
        }

        protected IronIntel.Contractor.Users.UserInfo GetCurrentUser()
        {
            var session = GetCurrentLoginSession();
            if (session == null)
            {
                return null;
            }
            return UserManagement.GetUserByIID(session.User.UID);
        }

        protected bool IsAdminOrSuper
        {
            get
            {
                var user = GetCurrentUser();
                if (user == null)
                {
                    return false;
                }
                return (user.UserType == UserTypes.Admin || user.UserType == UserTypes.SupperAdmin);
            }
        }

        public override string GetIronSystemServiceAddress()
        {
            return SystemParams.SystemServiceAddresses[0];
        }

        protected virtual bool AllowCurrentLoginSessionEnter()
        {
            var session = GetCurrentLoginSession();
            if (session == null)
            {
                return false;
            }
            if (string.Compare(session.User.CompanyID, SystemParams.CompanyID, true) == 0)
            {
                return true;
            }
            if (string.Compare(session.User.CompanyID, CompanyInfo.FORESIGHT, true) == 0)
            {
                return true;
            }
            return CreateClient<Foresight.Fleet.Services.User.UserQueryClient>().CanEnterSite(session.SessionID, SystemParams.CompanyID);
        }

        protected virtual bool ThrowIfNotAllowed { get { return false; } }

        protected bool CheckLoginSession()
        {
            var session = GetCurrentLoginSession();
            if (session == null)
            {
                RedirectToLoginPage();
                return false;
            }
            if (!AllowCurrentLoginSessionEnter())
            {
                if (ThrowIfNotAllowed)
                {
                    throw new Exception("The user was not allowed to enter this page.");
                }
                else
                {
                    string entry = GetUserDefaultEntryPageUrl(session.User);
                    if (string.IsNullOrEmpty(entry))
                        Response.Redirect(entry, true);
                    else
                        Response.Redirect(LoginPageUrl, true);
                }
                return false;
            }
            return true;
        }

        protected void DoLogout()
        {
            string sid = null;
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    sid = session.SessionID;
                }
            }
            catch { }
            try
            {
                ClearLoginSessionCookie();
            }
            catch { }
            if (sid != null)
            {
                try
                {
                    CreateClient<Foresight.Fleet.Services.User.UserQueryClient>().LogoutWithSessionID(sid);
                }
                catch
                {
                    // nothing
                }
            }

            RedirectToLoginPage();
        }

        protected void AddLog(string type, string source, string message, string detail)
        {
            try
            {
                SystemParams.WriteLog(type, source, message, detail);
            }
            catch
            {
                // nothing
            }
        }

        protected string GenerateUrl(string file)
        {
            string url;
            System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
            if (page != null)
            {
                // Use page instance.
                url = page.ResolveUrl("~/") + file;
            }
            else
            {
                // avoid duplicate operation
                url = System.Web.HttpContext.Current.Request.ApplicationPath + "/" + file;
            }
            try
            {
                var path = System.IO.Path.Combine(System.Web.HttpContext.Current.Request.PhysicalApplicationPath, file);
                if (System.IO.File.Exists(path))
                {
                    url += "?t=" + System.IO.File.GetLastWriteTimeUtc(path).Ticks;
                }
            }
            catch (Exception)
            {
                // cant read file
            }
            return url;
        }

        protected byte[] ConvertFile2bytes(HttpPostedFile uploadFile)
        {
            byte[] dataBuffer = new byte[uploadFile.InputStream.Length];
            uploadFile.InputStream.Position = 0;
            uploadFile.InputStream.Read(dataBuffer, 0, dataBuffer.Length);
            uploadFile.InputStream.Close();
            return dataBuffer;
        }

        public virtual string JQueryVersion
        {
            get { return "1.8.0"; }
        }

        protected T CreateClient<T>(string companyid = null) where T : RemoteClientBase
        {
            var session = GetCurrentLoginSession();
            return FleetServiceClientHelper.CreateClient<T>(companyid, session == null ? "" : session.SessionID);
        }
    }
}
