using FI.FIC;
using FI.FIC.Contracts.DataObjects.BaseObject;
using FI.FIC.Contracts.DataObjects.BLObject;
using FI.FIC.Contracts.DataObjects.Enumeration;
using FI.FIC.Models;
using FI.FIC.Models.Schedule;
using Foresight.Fleet.Services;
using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services.Customer;
using Foresight.Fleet.Services.JobSite;
using Foresight.ServiceModel;
using IronIntel.Contractor.ExportExcel;
using IronIntel.Contractor.JobSites;
using IronIntel.Contractor.Machines;
using IronIntel.Contractor.Maintenance;
using IronIntel.Contractor.MapView;
using IronIntel.Contractor.Site.Maintenance;
using IronIntel.Contractor.Users;
using Microsoft.SqlServer.Server;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Web;

namespace IronIntel.Contractor.Site
{
    public class UserManageBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string methodName)
        {
            object result = null;
            try
            {
                if (methodName != null)
                {
                    switch (methodName.ToUpper())
                    {
                        case "GETUSERS":
                            result = GetUsers();
                            break;
                        case "ADDUSER":
                            result = SaveUser(true);
                            break;
                        case "EDITUSER":
                            result = SaveUser(false);
                            break;
                        case "UPDATEUSER":
                            result = UpdateUser();
                            break;
                        case "DELETEUSER":
                            result = DeleteUser();
                            break;
                        case "RESETPASSWORD":
                            result = ResetPassword();
                            break;
                        case "GETUSERMACHINEGROUP":
                            result = GetUserMachineGroup();
                            break;
                        case "SAVEUSERMACHINEGROUP":
                            result = SaveUserMachineGroup();
                            break;
                        case "GETUSERINFO":
                            result = GetUserInfo();
                            break;
                        case "GETALLGROUPS":
                            result = GetAllGroups();
                            break;
                        case "GETGROUPSBYUSER":
                            result = GetGroupsByUser();
                            break;
                        case "GETSELECTEDMACHINES":
                            result = GetSelectedMachines();
                            break;
                        case "GETSELECTEDASSETS":
                            result = GetSelectedAssets();
                            break;
                        case "ASSIGNASSETSTOUSER":
                            result = AssignAssetsToUser();
                            break;
                        case "REMOVEASSIGNEDASSETSFROMUSER":
                            result = RemoveAssignedAssetsFromUser();
                            break;
                        case "SAVECONTACTMACHINES":
                            result = SaveContactMachines();
                            break;
                        case "GETJOBSITELIST":
                            result = GetJobsiteList();
                            break;
                        case "GETSELECTEDJOBSITES":
                            result = GetSelectedJobsites();
                            break;
                        case "GETUSERASSIGNEDJOBSITES":
                            result = GetUserAssignedJobsites();
                            break;
                        case "SAVECONTACTJOBSITES":
                            result = SaveContactJobsites();
                            break;
                        case "GETMACHINETYPES":
                            Machines.MachineManagement.RefreshMachineTypes();
                            result = MachineManagement.GetMachineTypes().OrderBy(m => m.Name).Select(t => new
                            {
                                ID = t.ID,
                                Name = t.Name
                            });
                            break;
                        case "GETMACHINELIST":
                            result = GetMachineList();
                            break;
                        case "GETFEATURESDEFINEDONUSER":
                            result = GetFeaturesDefinedOnUser();
                            break;
                        case "GETFEATURESMOUDULES":
                            result = GetFeaturesMoudules();
                            break;
                        case "GETASSETGROUPLIST":
                            result = GetAssetGroupList();
                            break;
                        case "GETSELECTEDASSETGROUPS":
                            result = GetSelectedAssetGroups();
                            break;
                        case "GETUSERASSIGNEDASSETGROUPS":
                            result = GetUserAssignedAssetGroups();
                            break;
                        case "GETLANGUAGES":
                            result = GetLanguages();
                            break;
                        case "GETASSETTYPES":
                            result = GetAssetTypes();
                            break;
                        case "GETSELECTEDASSETTYPES":
                            result = GetSelectedAssetTypes();
                            break;
                        case "GETUSERASSIGNEDASSETTYPES":
                            result = GetUserAssignedAssetTypes();
                            break;
                        case "SAVEUSERASSETTYPES":
                            result = SaveUserAssetTypes();
                            break;
                        case "GETLOCATIONSANDDEPARTMENTS":
                            result = GetLocationsAndDepartments();
                            break;
                        case "GETIMPORTUSERCOLUMNS":
                            result = GetImportUserColumns();
                            break;
                        case "IMPORTUSERS":
                            result = ImportUsers();
                            break;
                        case "GETMESSAGETYPES":
                            result = GetMessageTypes();
                            break;
                        case "COPYUSERBYIID":
                            result = CopyUser();
                            break;
                        case "GETUSERADDITIONALATTRIBUTE":
                            result = GetUserAdditionalAttribute();
                            break;
                        case "UPDATEUSERADDITIONALATTRIBUTE":
                            result = UpdateUserAdditionalAttribute();
                            break;
                        case "GETFILTERTEMPLATES":
                            result = GetFilterTemplates();
                            break;
                        case "GETFILTERTEMPLATEITEM":
                            result = GetFilterTemplateItem();
                            break;
                        case "GETIMPORTUSERPERMISSIONITEMS":
                            result = GetImportUserPermissionItems();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "ContactBasePage", ex.Message, ex.ToString());
                throw ex;
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

        private object CopyUser()
        {
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                try
                {
                    string copyUserIID = HttpUtility.HtmlDecode(Request.Form["CopyUserIID"]);
                    string userID = HttpUtility.HtmlDecode(Request.Form["UserID"]);
                    string userName = HttpUtility.HtmlDecode(Request.Form["UserName"]);
                    string password = HttpUtility.HtmlDecode(Request.Form["PWD"]);
                    string mobile = HttpUtility.HtmlDecode(Request.Form["Mobile"]);
                    string fob = HttpUtility.HtmlDecode(Request.Form["FOB"]);
                    var client = CreateClient<Foresight.Fleet.Services.User.UserQueryClient>();

                    string useriid = client.CopyUser(SystemParams.CompanyID, copyUserIID, userID, userName, password, mobile, fob, session.User.UID);

                    try
                    {
                        Guid _g = new Guid(useriid);
                        return useriid;
                    }
                    catch (Exception ex)
                    {
                        return "@error@" + useriid;
                    }
                }
                catch (Exception ex)
                {
                    return "@error@" + ex.Message;
                }

            }
            return "";
        }

        private object GetUserAdditionalAttribute()
        {
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                try
                {
                    string p = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    var client = CreateClient<Foresight.Fleet.Services.User.UserQueryClient>(SystemParams.CompanyID);

                    Foresight.Fleet.Services.User.UserAdditionalAttribute attrs = client.GetUserAdditionalAttribute(p);

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

        private object UpdateUserAdditionalAttribute()
        {
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                try
                {
                    string p = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    string[] ps = JsonConvert.DeserializeObject<string[]>(p);
                    var attrs = JsonConvert.DeserializeObject<Foresight.Fleet.Services.User.UserAdditionalAttribute>(ps[1]);
                    attrs.UserIID = ps[0];

                    var client = CreateClient<Foresight.Fleet.Services.User.UserQueryClient>(SystemParams.CompanyID);
                    client.UpdateUserAdditionalAttribute(ps[0], attrs);
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
            return "";
        }

        #region Security

        private object GetFeaturesDefinedOnUser()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var useriid = Request.Form["ClientData"];
                    return GetFeaturesDefined(useriid);
                }
                else
                    return new FeatureModuleItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private FeatureModuleItem[] GetFeaturesDefined(string useriid)
        {
            var client = CreateClient<Foresight.Fleet.Services.User.PermissionProvider>();
            Tuple<Foresight.Fleet.Services.User.Feature, Foresight.Fleet.Services.User.Permissions[]>[] features = client.GetFeaturesDefinedOnUser(SystemParams.CompanyID, useriid);

            if (features == null || features.Length == 0)
                return new FeatureModuleItem[0];

            List<FeatureModuleItem> list = new List<FeatureModuleItem>();
            List<int> exceptModules = new List<int>()
                    {
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_MAPVIEW,
                        //Foresight.Fleet.Services.User.FeatureModule.MODULE_JOBSITES,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_CREDENTIAL,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_SECURITY,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_FICMANAGEMENT,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_TEAM
                    };
            List<int> exceptFeatures = new List<int>() {
                        Foresight.Fleet.Services.User.Feature.ASSET_GROUP,
                        Foresight.Fleet.Services.User.Feature.MAINTENANCE_RECORD,
                        //Foresight.Fleet.Services.User.Feature.JOB_SITES_REQUIREMENTS,
                        //Foresight.Fleet.Services.User.Feature.JOB_SITES_DISPATCHREQUESTS,
                        //Foresight.Fleet.Services.User.Feature.JOB_SITES_SCHEDULER
                    };
            foreach (var feature in features)
            {
                if (exceptModules.Contains(feature.Item1.ModuleId))
                    continue;
                if (exceptFeatures.Contains(feature.Item1.Id))
                    continue;
                FeatureModuleItem fmi = list.FirstOrDefault(m => m.Module.Id == feature.Item1.ModuleId);

                if (fmi == null)
                {
                    fmi = new FeatureModuleItem();
                    fmi.Module = Foresight.Fleet.Services.User.FeatureModule.GetModule(feature.Item1.ModuleId);
                    fmi.Features.Add(feature);
                    list.Add(fmi);
                }
                else
                    fmi.Features.Add(feature);
            }

            return list.ToArray();
        }


        #endregion

        protected override bool AllowCurrentLoginSessionEnter()
        {
            var f = base.AllowCurrentLoginSessionEnter();
            if (!f)
            {
                return false;
            }

            // check whether you are admin.
            var session = GetCurrentLoginSession();
            if (session == null || session.User == null)
            {
                return false;
            }
            var ui = UserManagement.GetUserByIID(session.User.UID);
            return ui != null && ui.UserType >= UserTypes.Admin;
        }

        protected override bool ThrowIfNotAllowed { get { return true; } }

        private object ImportUsers()
        {
            try
            {
                int count = 0;
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string p = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    StringKeyValue[] kvs = JsonConvert.DeserializeObject<StringKeyValue[]>(p);

                    HttpPostedFile uploadFile = null;
                    byte[] iconfilebyte = null;
                    if (Request.Files.Count > 0)
                    {
                        uploadFile = Request.Files[0];
                        iconfilebyte = ConvertFile2bytes(uploadFile);
                    }

                    if (iconfilebyte != null)
                    {
                        DataTable dt = new ExportExcel.ImportFromExcel().LoadExcelData(iconfilebyte);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            var userclient = CreateClient<Foresight.Fleet.Services.User.UserQueryClient>();
                            var contactclient = CreateClient<Foresight.Fleet.Services.User.ContactClient>();
                            var upclient = CreateClient<Foresight.Fleet.Services.User.UserProfileProvider>();
                            var perclient = CreateClient<Foresight.Fleet.Services.User.PermissionProvider>();
                            var msgclient = CreateClient<MessageProvider>();
                            foreach (DataRow dr in dt.Rows)
                            {
                                try
                                {
                                    Users.UserObject userobject = ConvertToUserItem(dr, kvs, session.User.UID);
                                    UserInfo user = userobject.UserInfo;
                                    if (string.IsNullOrEmpty(user.ID))
                                    {
                                        continue;
                                    }
                                    if (!user.IsUser)
                                    {
                                        user.AllowLoginIntoFleetMobile = false;
                                        user.AllowLoginIntoInspectMobile = false;
                                        user.AllowLoginIntoPC = false;
                                        user.AllowMobileBarcodeScanning = false;
                                    }
                                    if (user.UserType == UserTypes.Admin || user.UserType == UserTypes.SupperAdmin)
                                    {
                                        user.UserType = UserTypes.Admin;
                                        user.AllowLoginIntoFleetMobile = true;
                                        user.AllowLoginIntoInspectMobile = true;
                                        user.AllowLoginIntoPC = true;
                                        user.AllowMobileBarcodeScanning = true;
                                    }

                                    Foresight.Fleet.Services.User.UserAdditionalAttribute atts = null;
                                    string userIID = "";
                                    if (string.IsNullOrWhiteSpace(user.IID))
                                    {
                                        if (string.IsNullOrWhiteSpace(user.TransPass))
                                        {
                                            user.TransPass = Guid.NewGuid().ToString().Replace("-", "");
                                        }
                                        if (string.IsNullOrEmpty(user.DisplayName))
                                        {
                                            user.DisplayName = user.ID;
                                        }
                                        userIID = UserManagement.AddUser(user, user.TransPass, session.User.UID, session.SessionID, Request.UserHostName, null);

                                        atts = new Foresight.Fleet.Services.User.UserAdditionalAttribute();
                                        atts.WorkOrderFollower = user.WorkOrderFollower;
                                        atts.ExcelExports = user.ExcelExports;
                                        atts.AccessAllAssets = true;
                                    }
                                    else
                                    {
                                        userIID = user.IID;
                                        UserManagement.UpdateUserInfo(user, session.User.UID, session.SessionID, Request.UserHostName, null);
                                        atts = userclient.GetUserAdditionalAttribute(userIID);
                                        atts.WorkOrderFollower = user.WorkOrderFollower;
                                        atts.ExcelExports = user.ExcelExports;
                                    }
                                    UserParams.SetStringParameter(userIID, "LandingPage", user.LandingPage);

                                    userclient.UpdateUserAdditionalAttribute(userIID, atts);
                                    if (user.GroupIDs != null)
                                    {
                                        contactclient.SaveUserGroups(SystemParams.CompanyID, userIID, user.GroupIDs);
                                    }
                                    if (user.LocationIds != null)
                                    {
                                        upclient.SaveUserLocations(SystemParams.CompanyID, userIID, user.LocationIds);
                                    }
                                    if (user.DepartmentIds != null)
                                    {
                                        upclient.SaveUserDepartments(SystemParams.CompanyID, userIID, user.DepartmentIds);
                                    }

                                    if (userobject.Features != null && userobject.Features.Length > 0 && (userobject.UserInfo.UserType < UserTypes.Admin || user.UserType == UserTypes.SupperAdmin))
                                    {
                                        perclient.UpdateFeaturesForUser(SystemParams.CompanyID, userIID, userobject.Features, session.User.UID);
                                    }
                                    if (userobject.MessageTypes != null && userobject.MessageTypes.Length > 0)
                                    {
                                        msgclient.UpdateMessageRestrictsForUser(SystemParams.CompanyID, userIID, userobject.MessageTypes);
                                    }

                                    count++;
                                }
                                catch (Exception e)
                                {
                                }
                            }
                        }
                    }
                }
                return count;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        Dictionary<string, int> departments = null;
        Dictionary<string, int> locations = null;
        Dictionary<string, string> groups = null;
        Dictionary<string, string> landPages = null;
        Dictionary<string, string> commonlandPages = null;
        private Users.UserObject ConvertToUserItem(DataRow dr, StringKeyValue[] kvs, string uid)
        {
            Users.UserObject userobject = new Users.UserObject();
            UserInfo user = new UserInfo();
            List<KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>> features = new List<KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>>();
            List<MessageRestrictInfo> messagetypes = new List<MessageRestrictInfo>();
            var userclient = CreateClient<Foresight.Fleet.Services.User.UserQueryClient>();

            StringKeyValue kv1 = kvs.FirstOrDefault(m => string.Compare(m.Key, "ID", true) == 0);
            if (kv1 == null || string.IsNullOrEmpty(kv1.Key) || string.IsNullOrEmpty(kv1.Value))
                return userobject;

            user.ID = dr[kv1.Value].ToString().Trim();
            if (string.IsNullOrEmpty(user.ID) || !Helper.IsEmail(user.ID))
            {
                throw new Exception("User ID/Email Error.");
            }

            UserInfo cuser = UserManagement.GetUserByID(user.ID);
            messagetypes = GetUserMessageTypes(cuser != null ? cuser.IID : "");
            if (cuser != null)
            {
                user = cuser;
                features = GetUserPermissions(user.IID);
                var att = userclient.GetUserAdditionalAttribute(user.IID);
                user.WorkOrderFollower = att.WorkOrderFollower;
                user.ExcelExports = att.ExcelExports;
                user.LandingPage = UserParams.GetStringParameter(user.IID, "LandingPage");
            }
            else
            {
                user.UserType = UserTypes.Readonly;
                user.ContactType = ContactTypes.Other;
                user.LandingPage = "MapView.aspx";
            }

            kv1 = kvs.FirstOrDefault(m => string.Compare(m.Key, "UserType", true) == 0);
            try
            {
                user.UserType = (UserTypes)(Convert.ToInt32(Enum.Parse(typeof(UserTypes), dr[kv1.Value].ToString().Trim(), true)));
            }
            catch
            {
            }

            if (string.IsNullOrWhiteSpace(user.IID) && user.UserType == UserTypes.Common)
            {
                KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]> feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(100, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(200, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(210, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(220, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(230, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(600, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(800, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(900, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(253, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(254, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(255, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(256, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
                feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(257, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                features.Add(feature);
            }

            foreach (StringKeyValue kv in kvs)
            {
                if (string.IsNullOrEmpty(kv.Key) || string.IsNullOrEmpty(kv.Value))
                {
                    continue;
                }

                if (dr[kv.Value] == DBNull.Value || dr[kv.Value] == null)
                {
                    continue;
                }

                #region User Fileds
                if (string.Compare(kv.Key, "DisplayName", true) == 0)
                {
                    user.DisplayName = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "Password", true) == 0)
                {
                    user.TransPass = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "TextAddress", true) == 0)
                {
                    user.TextAddress = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "Mobile", true) == 0)
                {
                    user.Mobile = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "BusinessPhone", true) == 0)
                {
                    user.BusinessPhone = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "IsUser", true) == 0)
                {
                    user.IsUser = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "WebBrowserAccess", true) == 0)
                {
                    user.AllowLoginIntoPC = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "Inspect", true) == 0)
                {
                    user.AllowLoginIntoInspectMobile = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "FleetApp", true) == 0)
                {
                    user.AllowLoginIntoFleetMobile = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "MobileApp", true) == 0)
                {
                    user.AllowMobileBarcodeScanning = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "ContactType", true) == 0)
                {
                    string s = dr[kv.Value].ToString().Trim().ToLower();
                    switch (s)
                    {
                        case "foreman":
                            user.ContactType = ContactTypes.Foreman;
                            break;
                        case "driver":
                            user.ContactType = ContactTypes.Driver;
                            break;
                        case "inventory manager":
                            user.ContactType = ContactTypes.InventoryManager;
                            break;
                        case "rental manager":
                            user.ContactType = ContactTypes.RentalManager;
                            break;
                        case "service manager":
                            user.ContactType = ContactTypes.ServiceManager;
                            break;
                        case "fleet manager":
                            user.ContactType = ContactTypes.FleetManager;
                            break;
                        case "technician":
                            user.ContactType = ContactTypes.Technician;
                            break;
                        case "advisor":
                            user.ContactType = ContactTypes.Advisor;
                            break;
                        default:
                            user.ContactType = ContactTypes.Other;
                            break;
                    }
                }
                else if (string.Compare(kv.Key, "AssignedWorkOrders", true) == 0)
                {
                    user.AssignedWorkOrders = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "OptOutOfEmail", true) == 0)
                {
                    user.EmailOptOut = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "InspectEmail", true) == 0)
                {
                    user.InspectEmailList = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "TeamIntelligenceUser", true) == 0)
                {
                    user.TeamIntelligenceUser = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "FOB", true) == 0)
                {
                    user.FOB = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "LandingPage", true) == 0)
                {
                    string lp = dr[kv.Value].ToString().Trim();
                    if (!string.IsNullOrEmpty(lp))
                    {
                        if (landPages == null)
                        {
                            landPages = new Dictionary<string, string>();
                            commonlandPages = new Dictionary<string, string>();
                            List<AppModuleInfo> allModule = Acl.GetAvailableAppModuleInfos(uid).Where(t => t.ModuleType == AppModuleType.System).ToList();

                            if (allModule != null && allModule.Count() > 0)
                            {
                                foreach (var l in allModule)
                                {
                                    if (l.ID == "250" || l.ID == "300" || l.ID == "350" || l.ID == "650")
                                    {
                                        landPages.Add(l.Name.ToLower(), l.Url);
                                        if (l.SubItems != null && l.SubItems.Count() > 0)
                                        {
                                            foreach (var s in l.SubItems)
                                            {
                                                if (s.FeatureID == 510 && s.ID == "nav_curfewmt")
                                                {
                                                    continue;
                                                }
                                                if (!landPages.ContainsKey(s.Title.ToLower()))
                                                {
                                                    landPages.Add(s.Title.ToLower(), s.Url);
                                                }
                                            }
                                        }
                                        continue;
                                    }
                                    landPages.Add(l.Name.ToLower(), l.Url);
                                    commonlandPages.Add(l.Name.ToLower(), l.Url);

                                    if (l.SubItems != null && l.SubItems.Count() > 0)
                                    {
                                        foreach (var s in l.SubItems)
                                        {
                                            if (s.FeatureID == 510 && s.ID == "nav_curfewmt")
                                            {
                                                continue;
                                            }
                                            if (!landPages.ContainsKey(s.Title.ToLower()))
                                            {
                                                landPages.Add(s.Title.ToLower(), s.Url);
                                            }
                                            if (s.FeatureID == 100 || s.FeatureID == 200 || s.FeatureID == 210 || s.FeatureID == 220 || s.FeatureID == 230)
                                            {
                                                if (!commonlandPages.ContainsKey(s.Title.ToLower()))
                                                {
                                                    commonlandPages.Add(s.Title.ToLower(), s.Url);
                                                }
                                            }
                                        }
                                    }
                                }

                            }
                        }
                        if (user.UserType == UserTypes.Common)
                        {
                            if (commonlandPages.ContainsKey(lp.ToLower().Trim()))
                            {
                                user.LandingPage = commonlandPages[lp.ToLower().Trim()];
                            }
                        }
                        else if ((int)user.UserType > 1)
                        {
                            if (landPages.ContainsKey(lp.ToLower().Trim()))
                            {
                                user.LandingPage = landPages[lp.ToLower().Trim()];
                            }
                        }
                    }
                }
                else if (string.Compare(kv.Key, "UserGroup", true) == 0)
                {
                    string gs = dr[kv.Value].ToString().Trim();
                    if (!string.IsNullOrEmpty(gs))
                    {
                        if (groups == null)
                        {
                            UserGroupInfo[] allgroups = UserManagement.GetGroups();
                            groups = new Dictionary<string, string>();
                            if (allgroups != null && allgroups.Length > 0)
                            {
                                foreach (var d in allgroups)
                                {
                                    if (groups.ContainsKey(d.Name.ToLower()))
                                    {
                                        groups[d.Name.ToLower()] = d.ID;
                                    }
                                    else
                                    {
                                        groups.Add(d.Name.ToLower(), d.ID);
                                    }
                                }
                            }
                        }

                        List<string> list = new List<string>();
                        string[] ss = gs.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                        if (ss != null && ss.Length > 0)
                        {
                            foreach (string s in ss)
                            {
                                if (groups.ContainsKey(s.ToLower().Trim()))
                                {
                                    list.Add(groups[s.ToLower().Trim()]);
                                }
                            }
                        }
                        user.GroupIDs = list.ToArray();
                    }
                }
                else if (string.Compare(kv.Key, "Department", true) == 0)
                {
                    string depts = dr[kv.Value].ToString().Trim();
                    if (!string.IsNullOrEmpty(depts))
                    {
                        if (departments == null)
                        {
                            var client = CreateClient<CustomerProvider>();
                            DepartmentInfo[] alldeps = client.GetAllDepartments(SystemParams.CompanyID);
                            departments = new Dictionary<string, int>();
                            if (alldeps != null && alldeps.Length > 0)
                            {
                                foreach (var d in alldeps)
                                {
                                    if (departments.ContainsKey(d.Name.ToLower()))
                                    {
                                        departments[d.Name.ToLower()] = d.Id;
                                    }
                                    else
                                    {
                                        departments.Add(d.Name.ToLower(), d.Id);
                                    }
                                }
                            }
                        }

                        List<int> list = new List<int>();
                        string[] ss = depts.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                        if (ss != null && ss.Length > 0)
                        {
                            foreach (string s in ss)
                            {
                                if (departments.ContainsKey(s.ToLower().Trim()))
                                {
                                    list.Add(departments[s.ToLower().Trim()]);
                                }
                            }
                        }
                        user.DepartmentIds = list.ToArray();
                    }
                }
                else if (string.Compare(kv.Key, "Location", true) == 0)
                {
                    string locs = dr[kv.Value].ToString().Trim();
                    if (!string.IsNullOrEmpty(locs))
                    {
                        if (locations == null)
                        {
                            var client = CreateClient<CustomerProvider>();
                            locations = new Dictionary<string, int>();
                            CustomerLocation[] alllocs = client.GetLocations(SystemParams.CompanyID);
                            if (alllocs != null && alllocs.Length > 0)
                            {
                                foreach (var l in alllocs)
                                {
                                    if (locations.ContainsKey(l.Name.ToLower()))
                                    {
                                        locations[l.Name.ToLower()] = l.ID;
                                    }
                                    else
                                    {
                                        locations.Add(l.Name.ToLower(), l.ID);
                                    }
                                }
                            }
                        }

                        List<int> list = new List<int>();
                        string[] ss = locs.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                        if (ss != null && ss.Length > 0)
                        {
                            foreach (string s in ss)
                            {
                                if (locations.ContainsKey(s.ToLower().Trim()))
                                {
                                    list.Add(locations[s.ToLower().Trim()]);
                                }
                            }
                        }
                        user.LocationIds = list.ToArray();
                    }
                }
                else if (string.Compare(kv.Key, "WorkOrderFollower", true) == 0)
                {
                    user.WorkOrderFollower = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "ExcelExports", true) == 0)
                {
                    user.ExcelExports = Helper.IsTrue(dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "PreferredLanguage", true) == 0)
                {
                    string language = "";
                    string langname = dr[kv.Value].ToString().Trim();
                    if (string.Compare("English", langname, true) == 0)
                        language = "en";
                    else if (string.Compare("English (United States)", langname, true) == 0)
                        language = "en-us";
                    else if (string.Compare("English (Canada)", langname, true) == 0)
                        language = "en-ca";
                    else if (string.Compare("English (Australia)", langname, true) == 0)
                        language = "en-au";
                    else if (string.Compare("English (Components)", langname, true) == 0)
                        language = "en-Components";
                    else if (string.Compare("français", langname, true) == 0)
                        language = "fr";
                    else if (string.Compare("français (France)", langname, true) == 0)
                        language = "fr-fr";
                    else if (string.Compare("français (Canada)", langname, true) == 0)
                        language = "fr-ca";

                    user.PreferredLanguage = language;
                }
                else if (string.Compare(kv.Key, "TimeZone", true) == 0)
                {
                    string tname = dr[kv.Value].ToString().Trim();
                    if (!string.IsNullOrWhiteSpace(tname))
                    {
                        string[] str = tname.Split(')');
                        if (str != null && str.Length > 1)
                            user.TimeZone = str[1];
                    }
                }


                #endregion

                #region Security

                else if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.ALERTS_MANAGEMENT.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.WORK_ORDER.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.FUEL_RECORDS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.CUSTOMER_RECORD.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.WORKORDERCONFIGURATION.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.REOPENWORKORDERS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.COMMUNICATEWITHCUSTOMER.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.WORKORDERSURVEYS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.WORKORDERGENERATOR.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.WORKORDERHISTORY.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.WORKORDERDELETEATTACHMENT.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.OPENWO_RESTRICTWORKORDERVIEW.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.CLOSEDWO_RESTRICTWORKORDERVIEW.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.CLOSEWORKORDERS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.DELETEANDRESTOREWORKORDERS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.OPENWORKORDERS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.JOB_SITES.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.JOB_SITES_AUTOCREATE.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.JOB_SITES_REQUIREMENTS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.JOB_SITES_DISPATCHREQUESTS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.JOB_SITES_SCHEDULER.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.PREVENTATIVE_MAINTENANCE.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.MAINTENANCE_RECORD.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.FILTERQ.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.MANAGE_ASSETS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.MANAGE_DEVICES.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.ASSET_ATTRIBUTE_ADJUSTMENT.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.ASSET_GROUP.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.M3.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.JOBSITE_LIMIT.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.HARSH_DRIVING.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.INSPECTION_TEMPLATES.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.INSPECTION_REPORTS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.REASSIGN_WORKORDERS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.TEAM_TEMPLATES.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                if (string.Compare(kv.Key, Foresight.Fleet.Services.User.Feature.TEAM_REPORTS.ToString(), true) == 0)
                {
                    SetUserPermissions(features, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                #endregion

                #region Messages 
                else if (string.Compare(kv.Key, "10", true) == 0)
                {
                    SetMessageTypeRestrict(messagetypes, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "20", true) == 0)
                {
                    SetMessageTypeRestrict(messagetypes, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "30", true) == 0)
                {
                    SetMessageTypeRestrict(messagetypes, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "40", true) == 0)
                {
                    SetMessageTypeRestrict(messagetypes, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "50", true) == 0)
                {
                    SetMessageTypeRestrict(messagetypes, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "60", true) == 0)
                {
                    SetMessageTypeRestrict(messagetypes, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "70", true) == 0)
                {
                    SetMessageTypeRestrict(messagetypes, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "80", true) == 0)
                {
                    SetMessageTypeRestrict(messagetypes, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "90", true) == 0)
                {
                    SetMessageTypeRestrict(messagetypes, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "100", true) == 0)
                {
                    SetMessageTypeRestrict(messagetypes, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                else if (string.Compare(kv.Key, "110", true) == 0)
                {
                    SetMessageTypeRestrict(messagetypes, Convert.ToInt32(kv.Key), dr[kv.Value].ToString().Trim());
                }
                #endregion
            }

            userobject.UserInfo = user;
            userobject.Features = features.ToArray();
            userobject.MessageTypes = messagetypes.ToArray();
            return userobject;
        }

        private List<KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>> GetUserPermissions(string useriid)
        {
            var client = CreateClient<Foresight.Fleet.Services.User.PermissionProvider>();
            Tuple<Foresight.Fleet.Services.User.Feature, Foresight.Fleet.Services.User.Permissions[]>[] features = client.GetFeaturesDefinedOnUser(SystemParams.CompanyID, useriid);

            if (features == null || features.Length == 0)
                return new List<KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>>();

            List<KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>> list = new List<KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>>();
            List<int> exceptModules = new List<int>()
                    {
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_MAPVIEW,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_CREDENTIAL,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_SECURITY,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_FICMANAGEMENT,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_TEAM
                    };
            List<int> exceptFeatures = new List<int>() {
                        Foresight.Fleet.Services.User.Feature.ASSET_GROUP,
                        Foresight.Fleet.Services.User.Feature.MAINTENANCE_RECORD,
                    };
            foreach (var feature in features)
            {
                if (exceptModules.Contains(feature.Item1.ModuleId))
                    continue;
                if (exceptFeatures.Contains(feature.Item1.Id))
                    continue;

                var kp = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(feature.Item1.Id, feature.Item2);
                list.Add(kp);
            }

            return list;
        }

        private void SetUserPermissions(List<KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>> features, int id, string s)
        {
            Foresight.Fleet.Services.User.Permissions[] permissions = null;
            if (string.Compare(s, "0", true) == 0 || string.Compare(s, "None", true) == 0)
                permissions = new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.None };
            else if (string.Compare(s, "1", true) == 0 || string.Compare(s, "ReadOnly", true) == 0 || string.Compare(s, "Read Only", true) == 0)
                permissions = new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.ReadOnly };
            else if (string.Compare(s, "2", true) == 0 || string.Compare(s, "MyWorkOrders", true) == 0 || string.Compare(s, "My Work Orders", true) == 0)
                permissions = new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.MyWorkOrders };
            else if (string.Compare(s, "10", true) == 0 || string.Compare(s, "RequestOnly", true) == 0 || string.Compare(s, "Request Only", true) == 0)
                permissions = new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.RequestOnly };
            else if (string.Compare(s, "11", true) == 0 || string.Compare(s, "MyLocationOrDepartment", true) == 0 || string.Compare(s, "My Location Or Department", true) == 0)
                permissions = new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.MyLocationOrDepartment };
            else if (string.Compare(s, "99999", true) == 0 || string.Compare(s, "FullControl", true) == 0 || string.Compare(s, "Full Control", true) == 0 || string.Compare(s, "All", true) == 0)
                permissions = new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl };
            else
                permissions = new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.None };

            KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]> feature = features.FirstOrDefault(m => m.Key == id);
            features.Remove(feature);
            features.Add(new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(id, permissions));
        }

        private void SetMessageTypeRestrict(List<MessageRestrictInfo> msgtypes, int id, string s)
        {
            MessageRestrictInfo kv = new MessageRestrictInfo();
            kv.MessageType = id;
            if (string.Compare(s, "0", true) == 0 || string.Compare(s, "None", true) == 0)
                kv.MessageType = ((int)Restricts.None);
            else if (string.Compare(s, "1", true) == 0 || string.Compare(s, "MyWorkOrders", true) == 0 || string.Compare(s, "My Work Orders", true) == 0)
                kv.MessageType = ((int)Restricts.MyWorkOrders);
            else if (string.Compare(s, "10", true) == 0 || string.Compare(s, "MyLocationOrDepartment", true) == 0 || string.Compare(s, "My Location Or Department", true) == 0)
                kv.MessageType = ((int)Restricts.MyLocationOrDepartment);
            else if (string.Compare(s, "99999", true) == 0 || string.Compare(s, "All", true) == 0 || string.Compare(s, "FullControl", true) == 0 || string.Compare(s, "Full Control", true) == 0)
                kv.MessageType = ((int)Restricts.All);
            else
                kv.MessageType = ((int)Restricts.None);

            MessageRestrictInfo msgtype = msgtypes.FirstOrDefault(m => m.MessageType == id);
            msgtypes.Remove(msgtype);
            msgtypes.Add(kv);
        }

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

                    HttpPostedFile uploadFile = null;
                    byte[] iconfilebyte = null;
                    if (Request.Files.Count > 0)
                    {
                        uploadFile = Request.Files[0];
                        iconfilebyte = ConvertFile2bytes(uploadFile);
                    }

                    if (iconfilebyte != null)
                    {
                        string[] columns = new ExportExcel.ImportFromExcel().LoadExcelColumnHead(iconfilebyte);
                        if (columns != null && columns.Length > 0)
                            return columns;
                    }
                }
                return new string[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetImportUserPermissionItems()
        {
            if (GetCurrentLoginSession() != null)
            {
                List<ImportUserPermissionItem> ls = new List<ImportUserPermissionItem>();
                var client = CreateClient<Foresight.Fleet.Services.User.PermissionProvider>();
                var features = client.GetAvailableFeatures(SystemParams.CompanyID);

                if (features != null && features.Length > 0)
                {
                    List<int> exceptModules = new List<int>()
                    {
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_MAPVIEW,
                        //Foresight.Fleet.Services.User.FeatureModule.MODULE_JOBSITES,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_CREDENTIAL,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_SECURITY,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_FICMANAGEMENT,
                        Foresight.Fleet.Services.User.FeatureModule.MODULE_TEAM
                    };
                    List<int> exceptFeatures = new List<int>() {
                        Foresight.Fleet.Services.User.Feature.ASSET_GROUP,
                        Foresight.Fleet.Services.User.Feature.MAINTENANCE_RECORD,
                        //Foresight.Fleet.Services.User.Feature.JOB_SITES_REQUIREMENTS,
                        //Foresight.Fleet.Services.User.Feature.JOB_SITES_DISPATCHREQUESTS,
                        //Foresight.Fleet.Services.User.Feature.JOB_SITES_SCHEDULER
                    };
                    foreach (var f in features)
                    {
                        ImportUserPermissionItem feature = new ImportUserPermissionItem();
                        feature.Id = Convert.ToInt32(f.Key);
                        feature.Name = f.Value;
                        feature.Type = 1;

                        if (exceptModules.Contains(Convert.ToInt32(f.Tag)))
                            continue;
                        if (exceptFeatures.Contains(feature.Id))
                            continue;

                        ls.Add(feature);
                    }
                }

                Foresight.Fleet.Services.MessageType[] messagetypes = Foresight.Fleet.Services.MessageType.MessageTypes;
                if (messagetypes != null && messagetypes.Length > 0)
                {
                    foreach (var f in messagetypes)
                    {
                        ImportUserPermissionItem kv = new ImportUserPermissionItem();
                        kv.Id = f.Id;
                        kv.Name = f.Name;
                        kv.Type = 2;
                        ls.Add(kv);
                    }
                }

                return ls.ToArray();
            }
            return "Failed";

        }
        private object GetUsers()
        {
            string p = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
            string[] ps = JsonConvert.DeserializeObject<string[]>(p);
            int active = Convert.ToInt32(ps[0]);
            var searchtxt = ps[1];
            var items = UserManagement.GetUsers(null, searchtxt).OrderBy(u => u.ID).ToArray();
            if (active == 1)
            {
                items = items.Where(m => m.Active).OrderBy(u => u.ID).ToArray();
            }
            else if (active == 0)
            {
                items = items.Where(m => !m.Active).OrderBy(u => u.ID).ToArray();
            }
            return items;
        }

        private object GetUserInfo()
        {
            var uid = Request.Form["ClientData"];
            var user = UserManagement.GetUserByIID(uid);
            user.LandingPage = UserParams.GetStringParameter(uid, "LandingPage");
            if (user == null)
                user = new UserInfo();

            var client = CreateClient<Foresight.Fleet.Services.User.UserProfileProvider>();
            user.LocationIds = client.GetLocationIdByUser(SystemParams.CompanyID, uid);
            user.DepartmentIds = client.GetDepartmentIdByUser(SystemParams.CompanyID, uid);

            return user;
        }

        private object SaveUser(bool adduser)
        {
            var session = GetCurrentLoginSession();
            if (session == null) return "";
            var ui = UserManagement.GetUserByIID(session.User.UID);

            var content = Request.Form["ClientData"];
            content = HttpUtility.HtmlDecode(content);
            var user = JsonConvert.DeserializeObject<Users.UserObject>(content);
            var item = user.UserInfo;

            byte[] avadarBytes = null;
            if (Request.Files.Count > 0)
            {
                HttpPostedFile uploadFile = Request.Files[0];
                avadarBytes = ConvertFile2bytes(uploadFile);
            }

            try
            {
                if (adduser)
                {
                    if (string.IsNullOrWhiteSpace(item.ID))
                    {
                        throw new ArgumentException("User ID cannot be empty.");
                    }
                    if (string.IsNullOrWhiteSpace(item.DisplayName))
                    {
                        throw new ArgumentException("User name cannot be empty.");
                    }
                    item.Active = true;
                    item.IID = UserManagement.AddUser(item, item.TransPass, session.User.UID, session.SessionID, Request.UserHostName, avadarBytes);
                    //if (item.UserType == UserTypes.Common)
                    //{
                    //    List<KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>> features = new List<KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>>();
                    //    KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]> feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(100, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                    //    features.Add(feature);
                    //    feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(200, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                    //    features.Add(feature);
                    //    feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(210, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                    //    features.Add(feature);
                    //    feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(220, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                    //    features.Add(feature);
                    //    feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(230, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                    //    features.Add(feature);
                    //    feature = new KeyValuePair<int, Foresight.Fleet.Services.User.Permissions[]>(600, new Foresight.Fleet.Services.User.Permissions[] { Foresight.Fleet.Services.User.Permissions.FullControl });
                    //    features.Add(feature);

                    //    var client = CreateClient<Foresight.Fleet.Services.User.PermissionProvider>();
                    //    client.UpdateFeaturesForUser(SystemParams.CompanyID, item.IID, features.ToArray(), session.User.UID);
                    //}
                    if (user.Features != null && user.Features.Length > 0
                       && (user.UserInfo.UserType < UserTypes.Admin || ui.UserType == UserTypes.SupperAdmin))
                    {
                        var client = CreateClient<Foresight.Fleet.Services.User.PermissionProvider>();
                        client.UpdateFeaturesForUser(SystemParams.CompanyID, item.IID, user.Features, session.User.UID);
                    }

                    var assetclient = CreateClient<AssetQueryClient>();
                    if (item.AssetIDs != null)//null说明前端没有加载，不做保存
                        assetclient.SaveUserAssets(SystemParams.CompanyID, item.IID, item.AssetIDs);
                    if (item.AssetGroupIDs != null)//null说明前端没有加载，不做保存
                        assetclient.SaveUserAssetGroups(SystemParams.CompanyID, item.IID, item.AssetGroupIDs);
                    if (item.JobsiteIDs != null)//null说明前端没有加载，不做保存
                        CreateClient<JobSiteProvider>().SaveUserJobsites(SystemParams.CompanyID, item.IID, item.JobsiteIDs);
                    if (item.AssetTypeIDs != null)//null说明前端没有加载，不做保存
                        assetclient.SaveUserAssetTypes(SystemParams.CompanyID, item.IID, item.AssetTypeIDs);
                }
                else
                {
                    UserManagement.UpdateUserInfo(item, session.User.UID, session.SessionID, Request.UserHostName, avadarBytes);
                    if (item.GroupIDs != null)
                    {
                        CreateClient<Foresight.Fleet.Services.User.ContactClient>().SaveUserGroups(SystemParams.CompanyID, item.IID, item.GroupIDs);
                    }
                    var assetclient = CreateClient<AssetQueryClient>();
                    if (item.AssetIDs != null)//null说明前端没有加载，不做保存
                        assetclient.SaveUserAssets(SystemParams.CompanyID, item.IID, item.AssetIDs);
                    if (item.AssetGroupIDs != null)//null说明前端没有加载，不做保存
                        assetclient.SaveUserAssetGroups(SystemParams.CompanyID, item.IID, item.AssetGroupIDs);
                    if (item.JobsiteIDs != null)//null说明前端没有加载，不做保存
                        CreateClient<JobSiteProvider>().SaveUserJobsites(SystemParams.CompanyID, item.IID, item.JobsiteIDs);
                    if (item.AssetTypeIDs != null)//null说明前端没有加载，不做保存
                        assetclient.SaveUserAssetTypes(SystemParams.CompanyID, item.IID, item.AssetTypeIDs);

                    // save subscribe message
                    if (user.Subscribe != null)
                    {
                        user.Subscribe.UserIID = item.IID;
                        List<UserAlertFilter> filters = null;
                        if (!string.IsNullOrEmpty(user.UserAlertFilter))
                        {
                            filters = JsonConvert.DeserializeObject<List<UserAlertFilter>>(user.UserAlertFilter);
                        }
                        FI.FIC.Models.WorkspaceManager.SaveSubscribeMessageByEmail(user.Subscribe, filters, item.IID);
                    }

                    if (user.Features != null && user.Features.Length > 0
                        && (user.UserInfo.UserType < UserTypes.Admin || ui.UserType == UserTypes.SupperAdmin))
                    {
                        var client = CreateClient<Foresight.Fleet.Services.User.PermissionProvider>();
                        client.UpdateFeaturesForUser(SystemParams.CompanyID, item.IID, user.Features, session.User.UID);
                    }
                    if (SystemParams.HasLicense("EmailSubscribe") && user.Schedule != null)
                    {
                        FI.FIC.Models.Schedule.ScheduleManager.SaveEmailScheduleItems(item.IID, user.Schedule, "en-us");
                    }
                }
                UserParams.SetStringParameter(item.IID, "LandingPage", item.LandingPage);
                var upclient = CreateClient<Foresight.Fleet.Services.User.UserProfileProvider>();
                upclient.SaveUserLocations(SystemParams.CompanyID, item.IID, item.LocationIds);
                upclient.SaveUserDepartments(SystemParams.CompanyID, item.IID, item.DepartmentIds);

                //FIC Alert Filter Templates
                var userfilterclient = CreateClient<Foresight.Fleet.Services.User.UserFilterProvider>();
                if (user.FilterTemplates != null && user.FilterTemplates.Length > 0)
                {
                    foreach (UserFilterTemplateItem filter in user.FilterTemplates)
                    {
                        if (filter.Id < 0)
                            filter.Id = userfilterclient.AddFilterTemplate(SystemParams.CompanyID, item.IID, filter.Name);
                        else
                            userfilterclient.ChangeFilterName(SystemParams.CompanyID, filter.Id, filter.Name);

                        long[] assetids = null;
                        if (filter.Assets != null && filter.Assets.Length > 0)
                            assetids = filter.Assets.Select(m => m.Id).ToArray();
                        userfilterclient.SetAssetFilter(SystemParams.CompanyID, filter.Id, assetids);

                        string[] assetgroups = null;
                        if (filter.AssetGroups != null && filter.AssetGroups.Length > 0)
                            assetgroups = filter.AssetGroups.Select(m => m.GroupID).ToArray();
                        userfilterclient.SetAssetGroupFilter(SystemParams.CompanyID, filter.Id, assetgroups);

                        int[] assettypes = null;
                        if (filter.AssetTypes != null && filter.AssetTypes.Length > 0)
                            assettypes = filter.AssetTypes.Select(m => m.ID).ToArray();
                        userfilterclient.SetAssetTypeFilter(SystemParams.CompanyID, filter.Id, assettypes);

                        long[] jobsites = null;
                        if (filter.Jobsites != null && filter.Jobsites.Length > 0)
                            jobsites = filter.Jobsites.Select(m => m.ID).ToArray();
                        userfilterclient.SetJobSiteFilter(SystemParams.CompanyID, filter.Id, jobsites);
                    }
                }
                if (user.DeleteFilterTemplates != null && user.DeleteFilterTemplates.Length > 0)
                {
                    foreach (int id in user.DeleteFilterTemplates)
                    {
                        userfilterclient.DeleteFilterTemplate(SystemParams.CompanyID, id);
                    }
                }

                if (user.MessageTypes != null && user.MessageTypes.Length > 0 && user.UserInfo.UserType != UserTypes.Readonly)
                {
                    var client = CreateClient<MessageProvider>();
                    client.UpdateMessageRestrictsForUser(SystemParams.CompanyID, item.IID, user.MessageTypes);
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            return new string[] { item.IID, "Saved successfully." };
        }

        private object UpdateUser()
        {
            var session = GetCurrentLoginSession();
            if (session == null) return "";
            var ui = UserManagement.GetUserByIID(session.User.UID);

            var content = Request.Form["ClientData"];
            content = HttpUtility.HtmlDecode(content);
            var item = JsonConvert.DeserializeObject<Users.UserInfo>(content);

            try
            {
                UserManagement.UpdateUserInfo(item, session.User.UID, session.SessionID, Request.UserHostName, null);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            return new string[] { item.IID, "Saved successfully." };
        }

        private string DeleteUser()
        {
            var session = GetCurrentLoginSession();
            if (session == null) return "";

            var iid = Request.Form["ClientData"];
            Guid guid;
            if (!Guid.TryParse(iid, out guid))
            {
                throw new ArgumentException("User IID is not valid.");
            }
            else if (!UserManagement.CanDeleteUser(iid))
            {
                throw new Exception("This user cannot be deleted.");
            }
            CreateClient<Foresight.Fleet.Services.User.UserQueryClient>().DeleteUser(iid, session.User.UID, "");
            return "OK";
        }

        private object ResetPassword()
        {
            var session = GetCurrentLoginSession();
            if (session == null) return "";
            var clientdata = Request.Form["ClientData"].Split((char)170);
            var iid = HttpUtility.HtmlDecode(clientdata[0]);
            var password = HttpUtility.HtmlDecode(clientdata[1]);

            Guid guid;
            if (!Guid.TryParse(iid, out guid))
            {
                throw new ArgumentException("User IID is not valid.");
            }

            UserManagement.ResetPassword(iid, password, session.User.UID, session.SessionID, Request.UserHostName);
            return "OK";
        }

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

                var allMachines = MachineManagement.GetMachineGroups("");
                var machines = MachineManagement.GetMachineGroupByUser(useriid);
                UserMachineGroupInfoItem mgi = new UserMachineGroupInfoItem();
                mgi.AllMachineGroups = allMachines.OrderBy((m) => m.GroupName).ToArray();
                mgi.MachineGroups = machines.OrderBy((m) => m.GroupName).ToArray();

                return mgi;
            }
            else
                return "OK";
        }
        private object SaveUserMachineGroup()
        {
            if (GetCurrentLoginSession() != null)
            {
                string clientdata = Request.Form["ClientData"];
                clientdata = HttpUtility.HtmlDecode(clientdata);
                UserMachineGroupSaveItem umg = JsonConvert.DeserializeObject<UserMachineGroupSaveItem>(clientdata);

                CreateClient<AssetQueryClient>().SaveUserAssetGroups(SystemParams.CompanyID, umg.UserIID, umg.GroupIDs);

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

        private object GetAllGroups()
        {
            if (GetCurrentLoginSession() != null)
            {
                var groups = UserManagement.GetGroups();
                return groups;
            }
            return "Failed";
        }

        private object GetGroupsByUser()
        {
            if (GetCurrentLoginSession() != null)
            {
                string clientdata = Request.Form["ClientData"];
                clientdata = HttpUtility.HtmlDecode(clientdata);

                var groups = UserManagement.GetGroupsByUser(clientdata);
                return groups;
            }
            return "Failed";
        }

        private MaintenanceMachineInfo[] GetSelectedMachines()
        {
            var contactid = Request.Form["ClientData"];
            var machines = MachineManagement.GetContactMachinesByID(contactid);

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

        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<AssetDataAdjustClient>(companyId).GetAssetsAssignedToUser(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
            {
                if (GetCurrentLoginSession() != 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<AssetDataAdjustClient>(companyId).AssignAssetsToUser(companyId, uid, ids);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private string RemoveAssignedAssetsFromUser()
        {
            try
            {
                if (GetCurrentLoginSession() != 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<AssetDataAdjustClient>(companyId).RemoveAssignedAssetsFromUser(companyId, uid, ids);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

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

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

                    CreateClient<AssetQueryClient>().SaveUserAssets(SystemParams.CompanyID, contactid, ids);
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetJobsiteList()
        {
            try
            {
                JobSiteItem[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    var s = Request.Form["ClientData"];
                    s = HttpUtility.HtmlDecode(s);

                    items = CreateClient<JobSiteProvider>().GetJobSiteItems(SystemParams.CompanyID, "", false);
                }
                else
                {
                    items = new JobSiteItem[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetSelectedJobsites()
        {
            try
            {
                JobSiteItem[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    var contactid = Request.Form["ClientData"];
                    contactid = HttpUtility.HtmlDecode(contactid);

                    items = CreateClient<JobSiteProvider>().GetUserJobsites(SystemParams.CompanyID, contactid);
                }
                else
                {
                    items = new JobSiteItem[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetUserAssignedJobsites()
        {
            try
            {
                JobSiteItem[] items = null;
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var uid = Request.Form["ClientData"];
                    uid = HttpUtility.HtmlDecode(uid);
                    if (string.IsNullOrWhiteSpace(uid))
                        uid = session.User.UID;

                    var ui = UserManagement.GetUserByIID(uid);
                    if (ui.UserType < UserTypes.Admin)
                    {
                        bool accessallassets = GetAccessAllAssets(uid);
                        if (accessallassets)
                            return GetJobsiteList();
                        else
                            items = CreateClient<JobSiteProvider>().GetUserJobsites(SystemParams.CompanyID, uid);

                    }
                    else
                        return GetJobsiteList();
                }
                else
                {
                    items = new JobSiteItem[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetAssetGroupList()
        {
            try
            {
                MachineGroup[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    items = MachineManagement.GetMachineGroups("").OrderBy((m) => m.GroupName).ToArray();
                }
                else
                {
                    items = new MachineGroup[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetSelectedAssetGroups()
        {
            try
            {
                var clientdata = Request.Form["ClientData"];
                var useriid = HttpUtility.HtmlDecode(clientdata);

                MachineGroup[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    items = MachineManagement.GetMachineGroupByUser(useriid).OrderBy((m) => m.GroupName).ToArray();
                }
                else
                {
                    items = new MachineGroup[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetUserAssignedAssetGroups()
        {
            try
            {
                MachineGroup[] items = null;
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var uid = Request.Form["ClientData"];
                    uid = HttpUtility.HtmlDecode(uid);
                    if (string.IsNullOrWhiteSpace(uid))
                        uid = session.User.UID;

                    var ui = UserManagement.GetUserByIID(uid);
                    if (ui.UserType < UserTypes.Admin)
                    {
                        bool accessallassets = GetAccessAllAssets(uid);

                        if (accessallassets)
                            return GetAssetGroupList();
                        else
                            items = MachineManagement.GetMachineGroupByUser(uid).OrderBy((m) => m.GroupName).ToArray();
                    }
                    else
                        return GetAssetGroupList();
                }
                else
                {
                    items = new MachineGroup[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

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

                    string[] ids = JsonConvert.DeserializeObject<string[]>(jobsiteids);
                    CreateClient<JobSiteProvider>().SaveUserJobsites(SystemParams.CompanyID, contactid, ids);

                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetAssetTypes()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    AssetType[] types = CreateClient<AssetClassProvider>().GetAssetTypes(SystemParams.CompanyID);
                    return types.OrderBy((t) => t.Name).ToArray();
                }
                else
                    return new AssetType[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetSelectedAssetTypes()
        {
            try
            {
                var clientdata = Request.Form["ClientData"];
                var useriid = HttpUtility.HtmlDecode(clientdata);

                AssetType[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    items = MachineManagement.GetMachineTypesByUser(useriid);
                }
                else
                {
                    items = new AssetType[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetUserAssignedAssetTypes()
        {
            try
            {
                AssetType[] items = null;
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var uid = Request.Form["ClientData"];
                    uid = HttpUtility.HtmlDecode(uid);
                    if (string.IsNullOrWhiteSpace(uid))
                        uid = session.User.UID;

                    var ui = UserManagement.GetUserByIID(uid);
                    if (ui.UserType < UserTypes.Admin)
                    {
                        bool accessallassets = GetAccessAllAssets(uid);
                        if (accessallassets)
                            return GetAssetTypes();
                        else
                            items = MachineManagement.GetMachineTypesByUser(uid);
                    }
                    else
                        return GetAssetTypes();
                }
                else
                {
                    items = new AssetType[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private string SaveUserAssetTypes()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var userid = HttpUtility.HtmlDecode(clientdata[0]);
                    var typeids = HttpUtility.HtmlDecode(clientdata[1]);

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

                    CreateClient<AssetQueryClient>().SaveUserAssetTypes(SystemParams.CompanyID, userid, ids);

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

        private object GetLocationsAndDepartments()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    FilterDataSourceItem item = new FilterDataSourceItem();
                    var client = CreateClient<CustomerProvider>();
                    CustomerLocation[] alllocs = client.GetLocations(SystemParams.CompanyID);
                    var plocs = alllocs.Where(d => d.PId <= 0).OrderBy(d => d.Name);
                    List<CustomerLocation> resultlocs = new List<CustomerLocation>();
                    foreach (var ploc in plocs)
                    {
                        resultlocs.Add(ploc);
                        resultlocs.AddRange(alllocs.Where(d => d.PId == ploc.ID).OrderBy(d => d.Name));
                    }
                    item.Locations = resultlocs.ToArray();

                    DepartmentInfo[] alldeps = client.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));
                    }
                    item.Departments = result.ToArray();

                    return item;
                }
                else
                    return new FilterDataSourceItem();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private MaintenanceMachineInfo[] GetMachineList()
        {
            var session = GetCurrentLoginSession();
            var s = Request.Form["ClientData"];
            var p = JsonConvert.DeserializeObject<StringKeyValue>(s);

            var machines = MaintenanceManagement.GetMaintenanceMachines(session.SessionID, int.Parse(p.Key), p.Value, session.User.UID)
                .OrderBy(m => m.DisplayName)
                .ToArray();

            return machines;
        }

        private object GetFeaturesMoudules()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    List<AppModuleInfo> list = Acl.GetAvailableAppModuleInfos(session.User.UID).ToList();
                    return list.ToArray();
                }
                else
                {
                    return new AppModuleInfo[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetLanguages()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    return CountryAndRegionCode.SupportedLanguages;
                }
                else
                {
                    throw new Exception("not login.");
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #region Message
        private object GetMessageTypes()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var useriid = HttpUtility.HtmlDecode(Request.Form["ClientData"]);

                    return GetMessageTypes(useriid);
                }
                else
                {
                    return new MessageTypeItem[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private MessageTypeItem[] GetMessageTypes(string useriid)
        {
            Foresight.Fleet.Services.MessageType[] messagetypes = Foresight.Fleet.Services.MessageType.MessageTypes;
            if (messagetypes == null)
                return new MessageTypeItem[0];

            List<MessageTypeItem> ls = new List<MessageTypeItem>();
            MessageRestrictInfo[] kvs = null;
            if (!string.IsNullOrEmpty(useriid))
                kvs = CreateClient<MessageProvider>().GetUserMessageRestricts(SystemParams.CompanyID, useriid);
            foreach (Foresight.Fleet.Services.MessageType type in messagetypes)
            {
                MessageTypeItem typeitem = new MessageTypeItem();
                Helper.CloneProperty(typeitem, type);
                typeitem.AvailableRestricts = typeitem.AvailableRestricts;

                if (kvs == null || kvs.Length == 0)
                {
                    typeitem.RestrictType = (int)Restricts.MyWorkOrders;
                }
                else
                {
                    MessageRestrictInfo kv = kvs.FirstOrDefault(m => m.MessageType == typeitem.Id);
                    typeitem.RestrictType = kv == null ? 1 : kv.RestrictType;
                    if (kv != null)
                    {
                        typeitem.AdditionalText = kv.AdditionalText;
                        typeitem.AdditionalEmail = kv.AdditionalEmail;
                    }
                }

                ls.Add(typeitem);
            }

            return ls.ToArray();
        }
        private List<MessageRestrictInfo> GetUserMessageTypes(string useriid)
        {
            Foresight.Fleet.Services.MessageType[] messagetypes = Foresight.Fleet.Services.MessageType.MessageTypes;
            if (messagetypes == null)
                return new List<MessageRestrictInfo>();

            List<MessageRestrictInfo> ls = new List<MessageRestrictInfo>();
            MessageRestrictInfo[] kvs = null;
            if (!string.IsNullOrEmpty(useriid))
                kvs = CreateClient<MessageProvider>().GetUserMessageRestricts(SystemParams.CompanyID, useriid);
            foreach (Foresight.Fleet.Services.MessageType type in messagetypes)
            {
                MessageRestrictInfo kv = new MessageRestrictInfo();
                kv.MessageType = type.Id;
                if (kvs == null || kvs.Length == 0)
                {
                    kv.RestrictType = (int)Restricts.MyWorkOrders;
                }
                else
                {
                    MessageRestrictInfo kv1 = kvs.FirstOrDefault(m => m.MessageType == type.Id);
                    if (kv != null)
                    {
                        kv = kv1;
                    }
                    else
                    {
                        kv.RestrictType = (int)Restricts.MyWorkOrders;
                    }
                }

                ls.Add(kv);
            }

            return ls;
        }

        #endregion

        #region user filter
        private object GetFilterTemplates()
        {
            try
            {
                var clientdata = Request.Form["ClientData"];
                string useriid = HttpUtility.HtmlDecode(clientdata);

                if (GetCurrentLoginSession() != null)
                {
                    var client = CreateClient<Foresight.Fleet.Services.User.UserFilterProvider>();
                    KeyValuePair<int, string>[] filters = client.GetFilterTemplates(SystemParams.CompanyID, useriid);
                    if (filters == null && filters.Length == 0)
                        return new KeyValuePair<int, string>[0];

                    return filters;
                }
                else
                {
                    return new KeyValuePair<int, string>[0];
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetFilterTemplateItem()
        {
            try
            {
                var clientdata = Request.Form["ClientData"].Split((char)170);
                string filteridstr = HttpUtility.HtmlDecode(clientdata[0]);
                int filterid = Convert.ToInt32(filteridstr);
                string useriid = HttpUtility.HtmlDecode(clientdata[1]);

                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var client = CreateClient<Foresight.Fleet.Services.User.UserFilterProvider>();

                    bool accessallassets = session.User.UserType >= Foresight.Fleet.Services.User.UserTypes.Admin;
                    if (!accessallassets)
                    {
                        Foresight.Fleet.Services.User.UserAdditionalAttribute attrs = CreateClient<Foresight.Fleet.Services.User.UserQueryClient>(SystemParams.CompanyID).GetUserAdditionalAttribute(useriid);
                        if (attrs != null)
                            accessallassets = attrs.AccessAllAssets;
                    }

                    UserFilterTemplateItem filter = new UserFilterTemplateItem();

                    List<AssetListItemInfo> lsasset = new List<AssetListItemInfo>();
                    var fassets = client.GetAssetFilter(SystemParams.CompanyID, filterid);
                    if (fassets != null && fassets.Length > 0)
                    {
                        AssetListItemInfo[] selitems = null;
                        if (!string.IsNullOrWhiteSpace(useriid))
                            selitems = CreateClient<AssetDataAdjustClient>(SystemParams.CompanyID).GetAssetsAssignedToUser(SystemParams.CompanyID, useriid);

                        foreach (var ai in fassets)
                        {
                            AssetListItemInfo item = new AssetListItemInfo();
                            item.Id = ai.Id;
                            item.Name = ai.Name;
                            item.VIN = ai.VIN;
                            item.MakeName = ai.MakeName;
                            item.ModelName = ai.ModelName;
                            item.TypeName = ai.TypeName;

                            if (accessallassets)
                                lsasset.Add(item);
                            else
                            {
                                if (selitems != null && selitems.Length > 0 && selitems.Select(m => m.Id).Contains(ai.Id))
                                    lsasset.Add(item);
                            }
                        }
                    }
                    filter.Assets = lsasset.ToArray();

                    List<MachineGroup> lsag = new List<MachineGroup>();
                    var fassetgroups = client.GetAssetGroupFilter(SystemParams.CompanyID, filterid);
                    if (fassetgroups != null && fassetgroups.Length > 0)
                    {
                        MachineGroup[] selitems = null;
                        if (!string.IsNullOrWhiteSpace(useriid))
                            selitems = MachineManagement.GetMachineGroupByUser(useriid).OrderBy((m) => m.GroupName).ToArray();
                        foreach (var kv in fassetgroups)
                        {
                            MachineGroup item = new MachineGroup();
                            item.GroupID = kv.Key;
                            item.GroupName = kv.Value;

                            if (accessallassets)
                                lsag.Add(item);
                            else
                            {
                                if (selitems != null && selitems.Length > 0 && selitems.Select(m => m.GroupID).Contains(kv.Key))
                                    lsag.Add(item);
                            }
                        }
                    }
                    filter.AssetGroups = lsag.ToArray();

                    List<AssetType> lstp = new List<AssetType>();
                    var fassettypes = client.GetAssetTypeFilter(SystemParams.CompanyID, filterid);
                    if (fassettypes != null && fassettypes.Length > 0)
                    {
                        AssetType[] selitems = null;
                        if (!string.IsNullOrWhiteSpace(useriid))
                            selitems = MachineManagement.GetMachineTypesByUser(useriid);
                        foreach (var kv in fassettypes)
                        {
                            AssetType item = new AssetType();
                            item.ID = kv.Key;
                            item.Name = kv.Value;
                            if (accessallassets)
                                lstp.Add(item);
                            else
                            {
                                if (selitems != null && selitems.Length > 0 && selitems.Select(m => m.ID).Contains(kv.Key))
                                    lstp.Add(item);
                            }
                        }
                    }
                    filter.AssetTypes = lstp.ToArray();

                    List<JobSiteItem> lsjs = new List<JobSiteItem>();
                    var fjobsites = client.GetJobsiteFilter(SystemParams.CompanyID, filterid);
                    if (fjobsites != null && fjobsites.Length > 0)
                    {
                        JobSiteItem[] selitems = null;
                        if (!string.IsNullOrWhiteSpace(useriid))
                            selitems = CreateClient<JobSiteProvider>().GetUserJobsites(SystemParams.CompanyID, useriid);
                        foreach (var kv in fjobsites)
                        {
                            JobSiteItem item = new JobSiteItem();
                            item.ID = kv.Key;
                            item.Name = kv.Value;
                            if (accessallassets)
                                lsjs.Add(item);
                            else
                            {
                                if (selitems != null && selitems.Length > 0 && selitems.Select(m => m.ID).Contains(kv.Key))
                                    lsjs.Add(item);
                            }
                        }
                    }
                    filter.Jobsites = lsjs.ToArray();

                    return filter;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        #endregion


        private bool GetAccessAllAssets(string uid)
        {
            bool accessallassets = false;
            var attrs = CreateClient<Foresight.Fleet.Services.User.UserQueryClient>(SystemParams.CompanyID).GetUserAdditionalAttribute(uid);
            if (attrs != null)
                accessallassets = attrs.AccessAllAssets;
            return accessallassets;
        }

        private class UserMachineGroupInfoItem
        {
            public MachineGroup[] AllMachineGroups { get; set; }
            public MachineGroup[] MachineGroups { get; set; }
        }
        private class UserMachineGroupSaveItem
        {
            public string UserIID { get; set; }
            public string[] GroupIDs { get; set; }
        }

        public class FeatureModuleItem
        {
            public Foresight.Fleet.Services.User.FeatureModule Module { get; set; }
            public List<Tuple<Foresight.Fleet.Services.User.Feature, Foresight.Fleet.Services.User.Permissions[]>> Features { get; set; } = new List<Tuple<Foresight.Fleet.Services.User.Feature, Foresight.Fleet.Services.User.Permissions[]>>();

        }

        public class MessageTypeItem
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int RestrictType { get; set; }
            public bool AdditionalText { get; set; }
            public bool AdditionalEmail { get; set; }
            public Restricts[] AvailableRestricts { get; set; }
        }
        public class ImportUserPermissionItem
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int Type { get; set; }
        }
    }
}
