using Foresight.Fleet.Services.JobSite;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Foresight.Fleet.Services.Partner;
using Foresight.Fleet.Services;
using IronIntel.Contractor.Users;
using Foresight.Fleet.Services.Asset;

namespace IronIntel.Contractor.Site.Customer
{
    public class CustomerRecordBasePage : ContractorBasePage
    {
        protected void ProcessRequest()
        {
            object result = null;
            try
            {
                string methodName = Request.Params["MethodName"];
                if (methodName != null)
                {
                    switch (methodName)
                    {
                        case "GetPartners":
                            result = GetPartners();
                            break;
                        case "GetCustomerRecordInfo":
                            result = GetPartner();
                            break;
                        case "SaveCustomerRecord":
                            result = SavePartner();
                            break;
                        case "DeletePartner":
                            result = DeletePartner();
                            break;
                        case "GetContacts":
                            result = GetContacts();
                            break;
                        case "SaveContact":
                            result = SaveContact();
                            break;
                        case "DeleteContact":
                            result = DeleteContact();
                            break;
                        case "GetCustomerComments":
                            result = GetComments();
                            break;
                        case "SubmitComment":
                            result = SubmitComment();
                            break;
                        case "GetAssignedMachines":
                            result = GetAssignedMachines();
                            break;
                        case "AssignMachines":
                            result = AssignMachines();
                            break;
                        case "RemoveAssignedMachines":
                            result = RemoveAssignedMachines();
                            break;
                        case "GetAssignedPartnersByMachine":
                            result = GetAssignedPartnersByMachine();
                            break;
                        case "GetSalespersons":
                            result = GetSalespersons();
                            break;
                        case "GetAllFollowers":
                            result = GetAllFollowers();
                            break;
                        case "GetFollowers":
                            result = GetFollowers();
                            break;
                        case "AddFollowers":
                            result = AddFollowers();
                            break;
                        case "DeleteFollower":
                            result = DeleteFollower();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "CustomerRecordBasePage", ex.Message, ex.ToString());
                throw ex;
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

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

                    BusinessPartnerInfo[] partners = CreateClient<BusinessPartnerProvider>().GetPartners(SystemParams.CompanyID, clientdata);
                    return partners;
                }
                else
                    return new BusinessPartnerInfo[0];

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

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

                    BusinessPartnerInfo partner = CreateClient<BusinessPartnerProvider>().GetPartner(SystemParams.CompanyID, Convert.ToInt32(id));
                    if (partner == null)
                        return new BusinessPartnerInfo();

                    return partner;
                }
                else
                    return new BusinessPartnerInfo();

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetAssignedPartnersByMachine()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    var assetid = HttpUtility.HtmlDecode(clientdata);

                    BusinessPartnerInfo[] partners = CreateClient<BusinessPartnerProvider>().GetAssignedPartnersByMachine(SystemParams.CompanyID, Convert.ToInt64(assetid));
                    return partners;
                }
                else
                    return new BusinessPartnerInfo[0];

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SavePartner()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    var data = HttpUtility.HtmlDecode(clientdata);
                    BusinessPartnerInfo partner = JsonConvert.DeserializeObject<BusinessPartnerInfo>(data);
                    if (partner.Id > 0)
                        CreateClient<BusinessPartnerProvider>().UpdatePartner(SystemParams.CompanyID, partner);
                    else
                        partner.Id = CreateClient<BusinessPartnerProvider>().AddNewPartner(SystemParams.CompanyID, partner);
                    return partner.Id;
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private string DeletePartner()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    var id = HttpUtility.HtmlDecode(clientdata);

                    CreateClient<BusinessPartnerProvider>().DeletePartner(SystemParams.CompanyID, Convert.ToInt32(id));
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

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

                    ContactInfo[] contacts = CreateClient<BusinessPartnerProvider>().GetContacts(SystemParams.CompanyID, int.Parse(custid));
                    if (contacts == null || contacts.Length == 0)
                        return new ContactInfo[0];

                    var lang = GetLanguageCookie();
                    List<ContactInfoClient> ls = new List<ContactInfoClient>();
                    foreach (var pa in contacts)
                    {
                        ContactInfoClient item = new ContactInfoClient();
                        Helper.CloneProperty(item, pa);
                        if ((int)item.ContactPreference == 0)
                            item.ContactPreferenceStr = SystemParams.GetTextByKey(lang, "P_CR_TEXT", "Text");
                        else if ((int)item.ContactPreference == 1)
                            item.ContactPreferenceStr = SystemParams.GetTextByKey(lang, "P_CR_EMAIL", "Email");
                        else if ((int)item.ContactPreference == 2)
                            item.ContactPreferenceStr = SystemParams.GetTextByKey(lang, "P_CR_PHONE", "Phone");
                        ls.Add(item);
                    }
                    return ls.ToArray(); ;
                }
                else
                    return new ContactInfoClient[0];

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private object SaveContact()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    int custid = int.Parse(ps[0]);
                    var data = HttpUtility.HtmlDecode(ps[1]);
                    ContactInfo contact = JsonConvert.DeserializeObject<ContactInfo>(data);
                    if (contact.Id > 0)
                        CreateClient<BusinessPartnerProvider>().UpdateContact(SystemParams.CompanyID, custid, contact);
                    else
                        contact.Id = CreateClient<BusinessPartnerProvider>().AddContact(SystemParams.CompanyID, custid, contact);
                    return contact.Id;
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private string DeleteContact()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    var id = HttpUtility.HtmlDecode(clientdata);

                    CreateClient<BusinessPartnerProvider>().DeleteContact(SystemParams.CompanyID, Convert.ToInt32(id));
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetAllFollowers()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var users = UserManagement.GetAllFollowers(session.SessionID);
                    return users;
                }
                else
                    return new UserInfo[0];

            }
            catch (Exception ex)
            {
                AddLog("ERROR", "CustomerRecordBasePage.GetAllFollowers", ex.Message, ex.ToString());
                return ex.Message;
            }
        }
        private object GetFollowers()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string custid = Request.Form["ClientData"];
                    custid = HttpUtility.HtmlDecode(custid);

                    FollowerInfo[] followers = CreateClient<BusinessPartnerProvider>().GetFollowers(SystemParams.CompanyID, int.Parse(custid));
                    if (followers == null || followers.Length == 0)
                        return new FollowerInfo[0];
                    return followers;
                }
                else
                    return new FollowerInfo[0];

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private object AddFollowers()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    int custid = int.Parse(ps[0]);
                    var data = HttpUtility.HtmlDecode(ps[1]);
                    FollowerInfo[] followers = JsonConvert.DeserializeObject<FollowerInfo[]>(data);
                    CreateClient<BusinessPartnerProvider>().AddFollowers(SystemParams.CompanyID, custid, followers);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private string DeleteFollower()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    var id = HttpUtility.HtmlDecode(clientdata);

                    CreateClient<BusinessPartnerProvider>().DeleteFollower(SystemParams.CompanyID, Convert.ToInt32(id));
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

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

                    CommentInfo[] comments = CreateClient<BusinessPartnerProvider>().GetComments(SystemParams.CompanyID, Convert.ToInt32(id));
                    if (comments == null || comments.Length == 0)
                        return new CommentItem[0];

                    List<CommentItem> ls = new List<CommentItem>();
                    foreach (CommentInfo com in comments)
                    {
                        CommentItem item = new CommentItem();
                        Helper.CloneProperty(item, com);
                        ls.Add(item);
                    }

                    return ls.OrderBy(r => r.SubmitLocalDate).ToArray();
                }
                else
                    return new CommentItem[0];

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private string SubmitComment()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    clientdata = HttpUtility.HtmlDecode(clientdata);
                    string[] p = JsonConvert.DeserializeObject<string[]>(clientdata);
                    int id = Convert.ToInt32(p[0]);
                    bool isprivate = Helper.IsTrue(p[1]);

                    CreateClient<BusinessPartnerProvider>().SubmitComment(SystemParams.CompanyID, id, p[2], isprivate);

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

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

                    var machines = CreateClient<BusinessPartnerProvider>().GetAssignedMachines(SystemParams.CompanyID, Convert.ToInt32(id)); if (session.User.UserType < Foresight.Fleet.Services.User.UserTypes.Admin)
                    {
                        AssetBasicInfo[] allassets = CreateClient<AssetQueryClient>(SystemParams.CompanyID).GetAssetBasicInfoByUser(SystemParams.CompanyID, "", session.User.UID, 0);
                        var allassetids = allassets.Select(a => a.ID).ToList();
                        machines = machines.Where(a => allassetids.Contains(a.Id)).ToArray();
                    }
                    return machines.OrderBy(m => m.VIN).Select(m => new
                    {
                        ID = m.Id,
                        Name = m.Name,
                        m.VIN,
                        m.MakeName,
                        m.ModelName,
                        m.TypeName
                    }).ToArray();
                }
                else
                    return new BusinessPartnerInfo[0];

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object AssignMachines()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    int id = Convert.ToInt32(ps[0]);
                    long[] assetids = JsonConvert.DeserializeObject<long[]>(ps[1]);

                    CreateClient<BusinessPartnerProvider>().AssignMachines(SystemParams.CompanyID, id, assetids);

                    return "OK";
                }
                else
                    return "Failed";

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object RemoveAssignedMachines()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    int id = Convert.ToInt32(ps[0]);
                    long[] assetids = JsonConvert.DeserializeObject<long[]>(ps[1]);

                    CreateClient<BusinessPartnerProvider>().RemoveAssignedMachines(SystemParams.CompanyID, id, assetids);

                    return "OK";
                }
                else
                    return "Failed";

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

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

                    var users = UserManagement.GetSalespersons(session.SessionID, SystemParams.CompanyID, searchtxt);
                    users = users.Where(m => !string.IsNullOrWhiteSpace(m.FOB)).OrderBy(m => m.FOB).ToArray();
                    return users;
                }
                else
                    return new UserInfo[0];

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

    }

    class CommentItem : CommentInfo
    {
        public string SubmitLocalDateStr { get { return SubmitLocalDate == null ? "" : SubmitLocalDate.ToString("M/d/yyyy h:mm:ss tt"); } }

    }

    public class ContactInfoClient : ContactInfo
    {
        public string ContactPreferenceStr { get; set; }
    }
}
