using Foresight.Data;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services.JobSite;
using Foresight.Fleet.Services.SystemOption;
using IronIntel.Contractor.Maintenance;
using IronIntel.Contractor.MapView;
using IronIntel.Contractor.Security;
using IronIntel.Contractor.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace IronIntel.Contractor.Site.Security
{
    public class CurfewBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string methodName)
        {
            object result = null;
            try
            {
                if (methodName != null)
                {
                    switch (methodName)
                    {
                        case "GetCurfews":
                            result = GetCurfews();
                            break;
                        case "GetCurfewInfo":
                            result = GetCurfewInfo();
                            break;
                        case "SaveCurfew":
                            result = SaveCurfew();
                            break;
                        case "GetUsers":
                            result = GetUsers();
                            break;
                        case "DeleteCurfew":
                            result = DeleteCurfew();
                            break;
                        case "GetSelectedAssets":
                            result = GetSelectedAssets();
                            break;
                        case "AssignAssetsToUser":
                            result = AssignAssetsToUser();
                            break;
                        case "RemoveAssignedAssetsFromUser":
                            result = RemoveAssignedAssetsFromUser();
                            break;
                        case "GetJobsiteList":
                            result = GetJobsiteList();
                            break;
                        case "GetSelectedJobsites":
                            result = GetSelectedJobsites();
                            break;
                        case "SaveCurfewJobsites":
                            result = SaveCurfewJobsites();
                            break;
                        case "GetCurfewMovementTolerance":
                            result = GetCurfewMovementTolerance();
                            break;
                        case "UpdateCurfewMovementTolerance":
                            result = UpdateCurfewMovementTolerance();
                            break;

                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "CurfewBasePage", ex.Message, ex.ToString());
                throw ex;
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

        private object GetCurfews()
        {
            try
            {
                var session = GetCurrentLoginSession();
                CurfewInfo[] items = null;
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var contractorid = HttpUtility.HtmlDecode(clientdata[0]);
                    var searchtext = HttpUtility.HtmlDecode(clientdata[1]);

                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;

                    items = CreateClient<CurfewClient>(contractorid).GetCurfews(contractorid, searchtext);
                }
                else
                {
                    items = new CurfewInfo[0];
                }
                return items.OrderBy(m => m.Title);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetCurfewInfo()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var contractorid = HttpUtility.HtmlDecode(clientdata[0]);
                    var curfewid = HttpUtility.HtmlDecode(clientdata[1]);

                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;

                    return CreateClient<CurfewClient>(contractorid).GetCurfewInfo(contractorid, curfewid);
                }
                else
                    return new CurfewInfo();

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object SaveCurfew()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var contractorid = HttpUtility.HtmlDecode(clientdata[0]);
                    var data = HttpUtility.HtmlDecode(clientdata[1]);

                    var ci = JsonConvert.DeserializeObject<CurfewInfo>(data);

                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;


                    ci.Id = CreateClient<CurfewClient>(contractorid).SaveCurfew(contractorid, ci);

                    return new string[] { ci.Id, "OK" };
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetUsers()
        {
            try
            {
                UserInfo[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    items = UserManagement.GetUsers();
                }
                else
                {
                    items = new UserInfo[0];
                }
                return items.OrderBy(m => m.ID);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private string DeleteCurfew()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var contractorid = HttpUtility.HtmlDecode(clientdata[0]);
                    var curfewid = HttpUtility.HtmlDecode(clientdata[1]);

                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;

                    CreateClient<CurfewClient>(contractorid).DeleteCurfew(contractorid, curfewid);

                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object[] GetSelectedAssets()
        {
            var clientdata = Request.Form["ClientData"].Split((char)170);
            var companyId = HttpUtility.HtmlDecode(clientdata[0]);
            if (string.IsNullOrEmpty(companyId))
            {
                companyId = SystemParams.CompanyID;
            }
            var uid = HttpUtility.HtmlDecode(clientdata[1]);

            var machines = CreateClient<CurfewClient>(companyId).GetAssetsAssignedToCurfew(companyId, uid);

            return machines.OrderBy(m => m.VIN).Select(m => new
            {
                ID = m.Id,
                Name = string.IsNullOrEmpty(m.Name2) ? m.Name : m.Name2,
                m.VIN,
                m.MakeName,
                m.ModelName,
                m.TypeName
            }).ToArray();
        }

        private string AssignAssetsToUser()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyId = HttpUtility.HtmlDecode(clientdata[0]);
                    if (string.IsNullOrEmpty(companyId))
                    {
                        companyId = SystemParams.CompanyID;
                    }
                    var uid = HttpUtility.HtmlDecode(clientdata[1]);
                    var machineids = HttpUtility.HtmlDecode(clientdata[2]);

                    var ids = JsonConvert.DeserializeObject<long[]>(machineids);

                    CreateClient<CurfewClient>(companyId).AssignAssetsToCurfew(companyId, uid, ids, session.User.UID);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private string RemoveAssignedAssetsFromUser()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var companyId = HttpUtility.HtmlDecode(clientdata[0]);
                    if (string.IsNullOrEmpty(companyId))
                    {
                        companyId = SystemParams.CompanyID;
                    }
                    var uid = HttpUtility.HtmlDecode(clientdata[1]);
                    var machineids = HttpUtility.HtmlDecode(clientdata[2]);

                    var ids = JsonConvert.DeserializeObject<long[]>(machineids);

                    CreateClient<CurfewClient>(companyId).RemoveAssetsFromCurfew(companyId, uid, ids, session.User.UID);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private object GetJobsiteList()
        {
            try
            {
                JobSiteViewItem[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    string contractorid = HttpUtility.HtmlDecode(clientdata[0]);
                    string searchtxt = HttpUtility.HtmlDecode(clientdata[1]);

                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;

                    var jss = CreateClient<JobSiteProvider>(contractorid).GetJobSiteItems(contractorid, "", false);
                    List<JobSiteViewItem> list = new List<JobSiteViewItem>();
                    foreach (var js in jss)
                    {
                        JobSiteViewItem item = new JobSiteViewItem();
                        item.ID = js.ID;
                        item.Name = js.Name;

                        list.Add(item);
                    }
                    items = list.ToArray();
                }
                else
                {
                    items = new JobSiteViewItem[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetSelectedJobsites()
        {
            try
            {
                JobSiteViewItem[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var contractorid = HttpUtility.HtmlDecode(clientdata[0]);
                    var curfewid = HttpUtility.HtmlDecode(clientdata[1]);

                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;
                    JobSiteItem[] jss = CreateClient<CurfewClient>(contractorid).GetJobSitesAssignedToCurfew(contractorid, curfewid);
                    List<JobSiteViewItem> list = new List<JobSiteViewItem>();
                    foreach (var js in jss)
                    {
                        JobSiteViewItem item = new JobSiteViewItem();
                        item.ID = js.ID;
                        item.Name = js.Name;

                        list.Add(item);
                    }
                    items = list.ToArray();
                }
                else
                {
                    items = new JobSiteViewItem[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private string SaveCurfewJobsites()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var contractorid = HttpUtility.HtmlDecode(clientdata[0]);
                    var curfewid = HttpUtility.HtmlDecode(clientdata[1]);
                    var jobsiteids = HttpUtility.HtmlDecode(clientdata[2]);

                    if (string.IsNullOrWhiteSpace(contractorid))
                        contractorid = SystemParams.CompanyID;

                    long[] ids = JsonConvert.DeserializeObject<long[]>(jobsiteids);

                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;

                    CreateClient<CurfewClient>(contractorid).AssignJobSitesToCurfew(contractorid, curfewid, ids);

                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        #region Curfew Movement Tolerance

        private object GetCurfewMovementTolerance()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    CurfewMovementTolerance tolerance = CreateClient<SystemOptionProvider>().GetCurfewMovementTolerance(SystemParams.CompanyID);
                    if (tolerance == null)
                    {
                        return new CurfewMovementToleranceInfo();
                    }

                    CurfewMovementToleranceInfo toleranceinfo = new CurfewMovementToleranceInfo();
                    toleranceinfo.DefaultTolerance = tolerance.DefaultTolerance;
                    if (tolerance.JobSites != null && tolerance.JobSites.Count > 0)
                    {
                        toleranceinfo.JobSites = new List<JobSiteCurfewMovementToleranceInfo>();
                        foreach (var js in tolerance.JobSites)
                        {
                            JobSiteCurfewMovementToleranceInfo jsi = new JobSiteCurfewMovementToleranceInfo();
                            Helper.CloneProperty(jsi, js);
                            toleranceinfo.JobSites.Add(jsi);
                        }
                    }

                    return toleranceinfo;
                }
                else
                {
                    return new CurfewMovementToleranceInfo();
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private string UpdateCurfewMovementTolerance()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    clientdata = HttpUtility.HtmlDecode(clientdata);

                    CurfewMovementToleranceInfo toleranceinfo = JsonConvert.DeserializeObject<CurfewMovementToleranceInfo>(clientdata);

                    CurfewMovementTolerance tolerance = new CurfewMovementTolerance();
                    tolerance.DefaultTolerance = toleranceinfo.DefaultTolerance;
                    foreach (JobSiteCurfewMovementToleranceInfo jsi in toleranceinfo.JobSites)
                    {
                        JobSiteCurfewMovementTolerance js = new JobSiteCurfewMovementTolerance();
                        Helper.CloneProperty(js, jsi);
                        tolerance.JobSites.Add(js);
                    }

                    CreateClient<SystemOptionProvider>().UpdateCurfewMovementTolerance(SystemParams.CompanyID, tolerance, session.User.UID);

                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion
    }
}
