using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Foresight;
using IronIntel.Contractor.Users;
using System.Web;
using Foresight.Fleet.Services.User;
using Foresight.Fleet.Services.FIC;

namespace IronIntel.Contractor.Site
{
    public class MainBasePage : ContractorBasePage
    {
        protected void ProcessRequest()
        {
            string methidName = Request.Params["MethodName"];
            switch (methidName)
            {
                case "GetUserData":
                    GetUserData();
                    break;
                case "GetAppModules":
                    GetAppModules();
                    break;
                case "GetVersions":
                    GetVersions();
                    break;
                case "GetSiteHeaderNote":
                    GetSiteHeaderNote();
                    break;
                case "SetFavorites":
                    SetFavorites();
                    break;
                case "GetFavoriteItems":
                    GetFavoriteItems();
                    break;
                case "GetDashboardList":
                    GetDashboardList();
                    break;
                case "SetRecentOpenedDashboard":
                    SetRecentOpenedDashboard();
                    break;
                case "UploadUserAvatar":
                    UploadUserAvatar();
                    break;
                default:
                    break;
            }
            //TODO
        }

        private void GetUserData()
        {
            string userdata = "";
            var session = GetCurrentLoginSession();
            if (session != null && session.User != null)
            {
                var data = new
                {
                    UserName = session.User.Name,
                };

                userdata = JsonConvert.SerializeObject(data);
            }

            Response.Write(userdata);
            Response.End();
        }

        private void UploadUserAvatar()
        {
            var session = GetCurrentLoginSession();
            if (session != null && session.User != null)
            {
                byte[] avadarBytes = null;
                if (Request.Files.Count > 0)
                {
                    HttpPostedFile uploadFile = Request.Files[0];
                    avadarBytes = ConvertFile2bytes(uploadFile);
                }
                UserManagement.SetUserAvatar(session.SessionID, session.User.UID, avadarBytes);
            }

            Response.Write(JsonConvert.SerializeObject("OK"));
            Response.End();
        }

        private void GetAppModules()
        {
            try
            {
                AppModuleInfo[] items = null;
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    List<AppModuleInfo> list = Acl.GetAvailableAppModuleInfos(session.User.UID).ToList();
                    //LicenseInfo license = SystemParams.GetLicense();
                    //if (license != null && license.Items.Count > 0)
                    //{
                    //    LicenseItem lijl = license.Items.FirstOrDefault(m => m.Key == "JOBSITELIMIT");
                    //    if (lijl == null || !Helper.IsTrue(lijl.Value))
                    //    {
                    //        AppModuleInfo item = list.FirstOrDefault(m => m.ID == "JOBSITELIMIT");
                    //        list.Remove(item);
                    //    }
                    //}
                    //if (!session.User.IsForesightUser)
                    //{
                    //    bool isallowed = UserManagement.CheckUserPermission(session.SessionID, session.User.UID, 30);
                    //    if (!isallowed)
                    //    {
                    //        AppModuleInfo item = list.FirstOrDefault(m => m.ID == "OTRConfig");
                    //        list.Remove(item);
                    //    }
                    //}
                    items = list.ToArray();
                }
                else
                {
                    items = new AppModuleInfo[0];
                }
                string json = JsonConvert.SerializeObject(items);
                Response.Write(json);
            }
            catch (Exception ex)
            {
                AddLog("Error", "GetAppModules", ex.Message, ex.ToString());
                Response.Write(JsonConvert.SerializeObject(ex.Message));
            }
            Response.End();
        }

        private void GetVersions()
        {
            List<string> versions = new List<string>();
            var session = GetCurrentLoginSession();
            if (session != null && session.User != null)
            {
                versions.Add(SystemParams.GetVersion());
                versions.Add(SystemParams.GetFICVersion());
            }

            string json = JsonConvert.SerializeObject(versions.ToArray());
            Response.Write(json);
            Response.End();
        }
        private void GetSiteHeaderNote()
        {
            string siteheadernote = "";
            var session = GetCurrentLoginSession();
            if (session != null && session.User != null)
            {
                siteheadernote = UserManagement.GetSiteHeaderNote(session.User.UID);
                if (string.IsNullOrEmpty(siteheadernote))
                {
                    var cust = FleetServiceClientHelper.CreateClient<Foresight.Fleet.Services.Customer.CustomerProvider>().GetCustomerDetail(SystemParams.CompanyID);
                    if (cust != null)
                        siteheadernote = cust.SiteHeaderNotes;
                }
            }
            string json = JsonConvert.SerializeObject(siteheadernote);
            Response.Write(json);
            Response.End();
        }

        private void GetFavoriteItems()
        {
            string value = string.Empty;
            var session = GetCurrentLoginSession();
            if (session != null && session.User != null)
            {
                value = UserParams.GetStringParameter(session.User.UID, "FavoriteSites");
            }

            string json = string.IsNullOrEmpty(value) ? JsonConvert.SerializeObject(new FavoriteInfo[0]) : value;
            Response.Write(json);
            Response.End();
        }


        private void SetFavorites()
        {
            var session = GetCurrentLoginSession();
            if (session != null && session.User != null)
            {
                var clientdata = Request.Form["ClientData"];
                var data = HttpUtility.HtmlDecode(clientdata);

                UserParams.SetStringParameter(session.User.UID, "FavoriteSites", data);
            }
            Response.Write(JsonConvert.SerializeObject("OK"));
            Response.End();
        }

        private void GetDashboardList()
        {
            List<DashboardInfo> ls = new List<DashboardInfo>();
            var session = GetCurrentLoginSession();
            if (session != null && session.User != null)
            {
                var ps = JsonConvert.DeserializeObject<string[]>(Request.Form["ClientData"]);
                var filter = HttpUtility.HtmlDecode(ps[0]);
                int flag;
                if (!int.TryParse(ps[1], out flag))
                {
                    flag = 0;
                }

                var ficprovider = FleetServiceClientHelper.CreateClient<FICObjectProvider>();
                WorkSpaceInfo[] wsps = ficprovider.GetWorkSpaces(SystemParams.CompanyID, filter, false, flag);
                ChartInfo[] charts = ficprovider.GetCharts(SystemParams.CompanyID, filter, flag);
                foreach (WorkSpaceInfo wsp in wsps)
                {
                    DashboardInfo item = new DashboardInfo();
                    Helper.CloneProperty(item, wsp);
                    item.IsChart = false;
                    item.Notes = wsp.Description;
                    ls.Add(item);
                }
                foreach (ChartInfo chart in charts)
                {
                    DashboardInfo item = new DashboardInfo();
                    Helper.CloneProperty(item, chart);
                    item.IsChart = true;
                    item.Notes = chart.ChartNotes;
                    ls.Add(item);
                }

                List<RecentOpenedDashboardItem> lsrencent = GetRecentOpenedDashboards(session.User.UID);
                foreach (RecentOpenedDashboardItem item in lsrencent)
                {
                    DashboardInfo dab = ls.FirstOrDefault(m => m.ID == item.ID);
                    if (dab != null)
                    {
                        ls.Remove(dab);
                        ls.Insert(0, dab);
                    }
                }
            }

            string json = JsonConvert.SerializeObject(ls.ToArray());
            Response.Write(json);
            Response.End();
        }

        private void SetRecentOpenedDashboard()
        {
            var session = GetCurrentLoginSession();
            if (session != null && session.User != null)
            {
                var clientdata = Request.Form["ClientData"];
                var id = HttpUtility.HtmlDecode(clientdata);

                List<RecentOpenedDashboardItem> lsrencent = GetRecentOpenedDashboards(session.User.UID);
                RecentOpenedDashboardItem ritem = lsrencent.FirstOrDefault(m => m.ID == id);
                if (ritem == null)
                {
                    RecentOpenedDashboardItem item = new RecentOpenedDashboardItem();
                    item.ID = id;
                    item.Time = DateTime.UtcNow;
                    lsrencent.Add(item);
                }
                else
                    ritem.Time = DateTime.UtcNow;

                lsrencent = lsrencent.OrderBy(m => m.Time).ToList();
                string newdata = JsonConvert.SerializeObject(lsrencent);
                UserParams.SetStringParameter(session.User.UID, "RecentOpenedDashboard", newdata);
            }
            Response.Write(JsonConvert.SerializeObject("OK"));
            Response.End();
        }

        private List<RecentOpenedDashboardItem> GetRecentOpenedDashboards(string uid)
        {
            string data = UserParams.GetStringParameter(uid, "RecentOpenedDashboard");
            List<RecentOpenedDashboardItem> ls = JsonConvert.DeserializeObject<List<RecentOpenedDashboardItem>>(data);
            if (ls == null)
                return new List<RecentOpenedDashboardItem>();
            return ls.OrderBy(m => m.Time).ToList();
        }
    }


    public class FavoriteInfo
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public int FavoriteType { get; set; }
    }

    public class DashboardInfo
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public string Description { get; set; }
        public string Notes { get; set; }
        public bool IsChart { get; set; }
    }

    public class RecentOpenedDashboardItem
    {
        public string ID { get; set; }
        public DateTime Time { get; set; }
    }

}
