using Foresight.Data;
using Foresight.Fleet.Services.JobSite;
using IronIntel.Contractor.Security;
using IronIntel.Contractor.Users;
using IronIntel.Services.Business.Admin;
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 JobsiteLimitBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string methodName)
        {
            object result = null;
            try
            {
                if (methodName != null)
                {
                    switch (methodName)
                    {
                        case "GetJobsiteLimits":
                            result = GetJobsiteLimits();
                            break;
                        case "SaveJobsiteLimit":
                            result = SaveJobsiteLimit();
                            break;
                        case "DeleteJobsiteLimit":
                            result = DeleteJobsiteLimit();
                            break;
                        case "GetContactList":
                            result = GetContactList();
                            break;
                        case "GetSelectedContacts":
                            result = GetSelectedContacts();
                            break;
                        case "SaveSubscribeContacts":
                            result = SaveSubscribeContacts();
                            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 GetJobsiteLimits()
        {
            try
            {
                if (GetCurrentLoginSession() != 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;

                    JobSiteLimitItem[] items = CreateClient<JobSiteProvider>(contractorid).GetJobSiteLimitItems(contractorid, searchtext);
                    if (items == null || items.Length == 0)
                        return new JobsiteLimitInfo[0];

                    MachineType[] alltypes = Machines.MachineManagement.GetMachineTypes();
                    List<JobsiteLimitInfo> list = new List<JobsiteLimitInfo>();
                    foreach (JobSiteLimitItem item in items)
                    {
                        JobsiteLimitInfo jl = new JobsiteLimitInfo();
                        Helper.CloneProperty(jl, item);
                        string[] typeids = jl.AssetTypes.Split(',');
                        if (typeids != null)
                        {
                            foreach (string tyid in typeids)
                            {
                                MachineType type = alltypes.FirstOrDefault(m => m.ID == Convert.ToInt32(tyid));
                                if (type != null)
                                {
                                    if (string.IsNullOrWhiteSpace(jl.AssetTypeNames))
                                        jl.AssetTypeNames = type.Name;
                                    else
                                        jl.AssetTypeNames += "," + type.Name;
                                }
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(searchtext))
                        {
                            if (Helper.Contains(jl.JobSiteName, searchtext) || Helper.Contains(jl.AssetTypeNames, searchtext) || Helper.Contains(jl.Notes, searchtext))
                                list.Add(jl);
                        }
                        else
                            list.Add(jl);
                    }

                    return list.OrderBy(m => m.ID);
                }
                else
                {
                    return new JobsiteLimitInfo[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

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

                    var jl = JsonConvert.DeserializeObject<JobsiteLimitInfo>(data);

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

                    JobSiteLimitItem item = new JobSiteLimitItem();
                    Helper.CloneProperty(item, jl);
                    var client = CreateClient<JobSiteProvider>(contractorid);
                    jl.ID = client.SaveJobSiteLimit(contractorid, item, session.User.UID);

                    if (jl.Active)
                        client.CheckOverUnderTruckingAlert(contractorid, jl.JobSiteID);

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

        private string DeleteJobsiteLimit()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var contractorid = HttpUtility.HtmlDecode(clientdata[0]);
                    var idstr = HttpUtility.HtmlDecode(clientdata[1]);
                    long id = Convert.ToInt64(idstr);

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

                    CreateClient<JobSiteProvider>(contractorid).DeleteJobSiteLimit(contractorid, id, string.Empty, session.User.UID);

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

        private UserInfo[] GetContactList()
        {
            var session = GetCurrentLoginSession();
            UserInfo[] users = null;
            if (session != null)
            {
                //contact = ContactManagement.GetContacts();
                users = UserManagement.GetActiveUsers(session.SessionID);
                users = users.OrderBy(u => u.DisplayName).ToArray();
            }
            else
            {
                users = new UserInfo[0];
            }
            return users;
        }
        private object GetSelectedContacts()
        {
            try
            {
                UserInfo[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    long id = Convert.ToInt64(clientdata);

                    items = JobsiteLimitManagement.GetSubscribeContacts(id);
                    items = items.OrderBy(u => u.DisplayName).ToArray();
                }
                else
                {
                    items = new UserInfo[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SaveSubscribeContacts()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var jlid = HttpUtility.HtmlDecode(clientdata[0]);
                    var contactids = HttpUtility.HtmlDecode(clientdata[1]);

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

                    JobsiteLimitManagement.SaveSubscribeContacts(jlid, ids);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
