using Foresight.Fleet.Services.Customer;
using Foresight.Standard;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace IronIntel.Contractor.Site.SystemSettings
{
    public class CustomerProviderBasePage : ContractorBasePage
    {
        protected bool IsDev
        {
            get
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    if (Helper.DevAccounts.Contains(session.User.ID, StringComparer.OrdinalIgnoreCase))
                        return true;
                }
                return false;
            }
        }

        protected void ProcessRequest(string methodName)
        {
            object result = null;
            try
            {
                if (methodName != null)
                {
                    switch (methodName.ToUpper())
                    {
                        case "GETCUSTOMERLOCATIONS":
                            result = GetCustomerLocations();
                            break;
                        case "SAVECUSTOMERLOCATION":
                            result = SaveCustomerLocation();
                            break;
                        case "DELETECUSTOMERLOCATION":
                            result = DeleteCustomerLocation();
                            break;
                        case "GETDEPARTMENTS":
                            result = GetDepartments();
                            break;
                        case "SAVEDEPARTMENT":
                            result = SaveDepartment();
                            break;
                        case "DELETEDEPARTMENT":
                            result = DeleteDepartment();
                            break;
                        case "GETREGIONS":
                            result = GetRegions();
                            break;
                        case "SAVEREGION":
                            result = SaveRegion();
                            break;
                        case "DELETEREGION":
                            result = DeleteRegion();
                            break;
                        case "GETSYSTEMPARAMS":
                            result = GetSystemParams();
                            break;
                        case "SETSYSTEMPARAMS":
                            result = SetSystemParams();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
                SystemParams.WriteLog("Error", "CustomerProvider.ProcessRequest", ex.Message, ex.ToString());
            }

            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }
        private object GetCustomerLocations()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    CustomerLocation[] alllocs = CreateClient<CustomerProvider>().GetLocations(SystemParams.CompanyID);
                    var plocs = alllocs.Where(d => d.PId <= 0).OrderBy(d => d.Name);
                    List<CustomerLocation> result = new List<CustomerLocation>();
                    foreach (var ploc in plocs)
                    {
                        result.Add(ploc);
                        result.AddRange(alllocs.Where(d => d.PId == ploc.ID).OrderBy(d => d.Name));
                    }
                    return result.ToArray();
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object SaveCustomerLocation()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string data = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    HttpPostedFile uploadFile = null;
                    byte[] logobyte = null;
                    if (Request.Files.Count > 0)
                    {
                        uploadFile = Request.Files[0];
                        logobyte = ConvertFile2bytes(uploadFile);
                    }

                    CustomerLocation location = JsonConvert.DeserializeObject<CustomerLocation>(data);
                    var cp = CreateClient<CustomerProvider>();
                    int locationid = location.ID;
                    if (locationid == -1)
                        locationid = cp.AddLocation(SystemParams.CompanyID, location);
                    else
                        cp.UpdateLocation(SystemParams.CompanyID, location);

                    if (logobyte != null)
                        cp.ChangeLocationLOGO(SystemParams.CompanyID, locationid, logobyte);
                    return "OK";
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteCustomerLocation()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string id = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    int locationid = -1;
                    int.TryParse(id, out locationid);
                    CreateClient<CustomerProvider>().DeleteLocation(SystemParams.CompanyID, locationid);

                    return new string[0];
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetDepartments()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    DepartmentInfo[] alldeps = CreateClient<CustomerProvider>().GetAllDepartments(SystemParams.CompanyID);
                    var pdeps = alldeps.Where(d => d.PId <= 0).OrderBy(d => d.Name);
                    List<DepartmentInfo> result = new List<DepartmentInfo>();
                    foreach (var pdep in pdeps)
                    {
                        result.Add(pdep);
                        result.AddRange(alldeps.Where(d => d.PId == pdep.Id).OrderBy(d => d.Name));
                    }
                    return result.ToArray();
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object SaveDepartment()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string data = HttpUtility.HtmlDecode(Request.Params["ClientData"]);

                    DepartmentInfo dep = JsonConvert.DeserializeObject<DepartmentInfo>(data);
                    var cp = CreateClient<CustomerProvider>();
                    if (dep.Id > 0)
                        cp.UpdateDepartment(SystemParams.CompanyID, dep);
                    else
                        dep = cp.AddNewDepartment(SystemParams.CompanyID, dep);

                    return dep.Id;
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteDepartment()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string id = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    int depid = -1;
                    int.TryParse(id, out depid);
                    CreateClient<CustomerProvider>().DeleteDepartment(SystemParams.CompanyID, depid);

                    return new string[0];
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #region Region
        private object GetRegions()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    RegionInfo[] regions = CreateClient<CustomerProvider>().GetRegions(SystemParams.CompanyID);

                    if (regions == null || regions.Length == 0)
                        return new RegionItem[0];

                    List<RegionItem> ls = new List<RegionItem>();
                    foreach (var region in regions)
                    {
                        RegionItem item = new RegionItem();
                        Helper.CloneProperty(item, region);
                        ls.Add(item);
                    }
                    return ls.ToArray();
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object SaveRegion()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string data = HttpUtility.HtmlDecode(Request.Params["ClientData"]);

                    RegionInfo region = JsonConvert.DeserializeObject<RegionInfo>(data);
                    var cp = CreateClient<CustomerProvider>();
                    if (region.Id > 0)
                        cp.UpdateRegion(SystemParams.CompanyID, region);
                    else
                        cp.AddNewRegion(SystemParams.CompanyID, region);

                    return new string[0];
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteRegion()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = HttpUtility.HtmlDecode(Request.Params["ClientData"]);
                    int id = -1;
                    int.TryParse(clientdata, out id);
                    CreateClient<CustomerProvider>().DeleteRegion(SystemParams.CompanyID, id);

                    return new string[0];
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        #region  System Params

        private object GetSystemParams()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    StringKeyValue[] items = CreateClient<CustomerProvider>().GetSystemParams(SystemParams.CompanyID);

                    if (items == null || items.Length == 0)
                        return new StringKeyValue[0];

                    return items;
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SetSystemParams()
        {
            try
            {
                if (GetCurrentLoginSession() != null && IsDev)
                {
                    string data = HttpUtility.HtmlDecode(Request.Params["ClientData"]);

                    string[] pstr = JsonConvert.DeserializeObject<string[]>(data);
                    var cp = CreateClient<CustomerProvider>();
                    cp.SetSystemParams(SystemParams.CompanyID, pstr[0], pstr[1]);

                    return "OK";
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion
    }

    class RegionItem : RegionInfo
    {
        public string StartDateStr { get { return StartDate == null ? "" : StartDate.Value.ToShortDateString(); } }
        public string EndDateStr { get { return EndDate == null ? "" : EndDate.Value.ToShortDateString(); } }
        public string ProjectedEndDateStr { get { return ProjectedEndDate == null ? "" : ProjectedEndDate.Value.ToShortDateString(); } }

    }
}
