using Foresight.Data;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services.JobSite;
using Foresight.Fleet.Services.SystemOption;
using IronIntel.Contractor.JobSites;
using IronIntel.Contractor.Maintenance;
using IronIntel.Contractor.MapView;
using IronIntel.Contractor.Security;
using IronIntel.Contractor.Users;
using IronIntel.Services.Customers;
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 "GetSelectedMachines":
                            result = GetSelectedMachines();
                            break;
                        case "SaveCurfewMachines":
                            result = SaveCurfewMachines();
                            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 "GetMachineList":
                            result = GetMachineList();
                            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]);

                    FISqlConnection contractordb = null;
                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;
                    else
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(contractorid);
                        contractordb = new FISqlConnection(connetionstring);
                    }

                    items = CurfewManagement.GetCurfews(session.SessionID, searchtext, contractordb);
                }
                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]);

                    FISqlConnection contractordb = null;
                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;
                    else
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(contractorid);
                        contractordb = new FISqlConnection(connetionstring);
                    }

                    return CurfewManagement.GetCurfewInfo(curfewid, contractordb);
                }
                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 (string.IsNullOrWhiteSpace(ci.CurfewID))
                    {
                        ci.CurfewID = Guid.NewGuid().ToString();
                    }

                    FISqlConnection contractordb = null;
                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;
                    else
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(contractorid);
                        contractordb = new FISqlConnection(connetionstring);
                    }

                    CurfewManagement.SaveCurfew(ci, GetCurrentLoginSession().User.UID, contractordb);

                    return new string[] { ci.CurfewID, "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]);

                    FISqlConnection contractordb = null;
                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;
                    else
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(contractorid);
                        contractordb = new FISqlConnection(connetionstring);
                    }

                    CurfewManagement.DeleteCurfew(curfewid, contractordb);

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

        private MaintenanceMachineInfo[] GetSelectedMachines()
        {
            var clientdata = Request.Form["ClientData"].Split((char)170);
            var contractorid = HttpUtility.HtmlDecode(clientdata[0]);
            var curfewid = HttpUtility.HtmlDecode(clientdata[1]);

            FISqlConnection contractordb = null;
            if (!SystemParams.IsDealer)
                contractorid = SystemParams.CompanyID;
            else
            {
                string connetionstring = SystemParams.GetDbStringByCompany(contractorid);
                contractordb = new FISqlConnection(connetionstring);
            }

            var machines = CurfewManagement.GetCurfewMachinesByID(curfewid, contractordb);

            return machines.OrderBy(m => m.VIN).ToArray();
        }

        private string SaveCurfewMachines()
        {
            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 machineids = HttpUtility.HtmlDecode(clientdata[2]);
                    if (string.IsNullOrWhiteSpace(contractorid))
                        contractorid = SystemParams.CompanyID;

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

                    FISqlConnection contractordb = null;
                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;
                    else
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(contractorid);
                        contractordb = new FISqlConnection(connetionstring);
                    }
                    CurfewManagement.SaveCurfewMachines(curfewid, contractorid, ids, contractordb);

                    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 MaintenanceMachineInfo[] GetMachineList()
        {
            var session = GetCurrentLoginSession();
            var clientdata = Request.Form["ClientData"].Split((char)170);
            string contractorid = HttpUtility.HtmlDecode(clientdata[0]);
            string type = HttpUtility.HtmlDecode(clientdata[1]);
            string searchtxt = HttpUtility.HtmlDecode(clientdata[2]);

            int typeid = 0;
            int.TryParse(type, out typeid);

            FISqlConnection contractordb = null;
            if (!SystemParams.IsDealer)
                contractorid = SystemParams.CompanyID;
            else
            {
                string connetionstring = SystemParams.GetDbStringByCompany(contractorid);
                contractordb = new FISqlConnection(connetionstring);
            }

            var machines = MaintenanceManagement.GetMaintenanceMachines(session.SessionID, typeid, searchtxt, session.User.UID, contractorid)
                .OrderBy(m => m.VIN)
                .ToArray();

            return machines;
        }

        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]);

                    FISqlConnection contractordb = null;
                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;
                    else
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(contractorid);
                        contractordb = new FISqlConnection(connetionstring);
                    }

                    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]);

                    FISqlConnection contractordb = null;
                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;
                    else
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(contractorid);
                        contractordb = new FISqlConnection(connetionstring);
                    }

                    items = CurfewManagement.GetCurfewJobsitesByID(curfewid, contractordb);
                }
                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;

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

                    FISqlConnection contractordb = null;
                    if (!SystemParams.IsDealer)
                        contractorid = SystemParams.CompanyID;
                    else
                    {
                        string connetionstring = SystemParams.GetDbStringByCompany(contractorid);
                        contractordb = new FISqlConnection(connetionstring);
                    }

                    CurfewManagement.SaveCurfewJobsites(curfewid, contractorid, ids, contractordb);

                    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
    }
}
