using FI.FIC.Contracts.DataObjects.BLObject;
using Foresight.Data;
using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services.AssetHealth.WorkOrder;
using Foresight.Fleet.Services.Device;
using Foresight.Fleet.Services.JobSite;
using Foresight.Fleet.Services.User;
using Foresight.ServiceModel;
using IronIntel.Contractor.ExportExcel;
using IronIntel.Contractor.Machines;
using IronIntel.Contractor.Maintenance;
using Microsoft.SqlServer.Server;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace IronIntel.Contractor.Site.Maintenance
{
    public class AlertsBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string method)
        {
            object result = null;
            try
            {
                string methodName = Request.Params["MethodName"];
                if (methodName != null)
                {
                    switch (methodName.ToUpper())
                    {
                        case "GETALERTS":
                            result = GetAlerts();
                            break;
                        case "GETMACHINEALERTS":
                            result = GetMachineAlerts();
                            break;
                        case "GETPMALERTSERVICEDESCRIPTIONS":
                            result = GetPMAlertServiceDescriptions();
                            break;
                        case "SAVEACKNOWLEDGEALERT":
                            result = SaveAcknowledgeAlert();
                            break;
                        case "ASSIGNEDALERTSTOWORKORDER":
                            result = AssignedAlertsToWorkOrder();
                            break;
                        case "GETALERTSLISENCE":
                            result = GetAlertsLisence();
                            break;
                        case "GETWORKORDERALERTS":
                            result = GetWorkOrderAlerts();
                            break;
                        case "GETASSETALERTS":
                            result = GetAssetAlerts();
                            break;
                        case "GETASSETGROUPS":
                            result = GetAssetGroups();
                            break;
                        case "GETALERTTYPES":
                            result = GetAlertTypes();
                            break;
                        case "GETACKNOWLEDGEDALERTS":
                            result = GetAcknowledgedAlerts();
                            break;
                        case "GETJOBSITES":
                            result = GetJobsites();
                            break;
                        case "GETALERTCATEGORY":
                            result = GetAlertCategory();
                            break;
                        case "SAVEAUTOACKNOWLEDGEALERTTYPES":
                            result = SaveAutoAcknowledgeAlertTypes();
                            break;
                        case "GETAUTOACKNOWLEDGEALERTTYPES":
                            result = GetAutoAcknowledgeAlertTypes();
                            break;
                        case "GETAUTOACKNOWLEDGEALERTTYPESHISTORY":
                            result = GetAutoAcknowledgeAlertTypesHistory();
                            break;
                        case "GETWORKORDERGENERATORS":
                            result = GetWorkOrderGenerators();
                            break;
                        case "SAVEWORKORDERGENERATOR":
                            result = SaveWorkOrderGenerator();
                            break;
                        case "DELETEWORKORDERGENERATOR":
                            result = DeleteWorkOrderGenerator();
                            break;
                        case "GETASSIGNTOS":
                            result = GetAssignTos();
                            break;
                        case "GETALERTMAPPINGS":
                            result = GetAlertMappings();
                            break;
                        case "SAVEALERTMAPPING":
                            result = SaveAlertMapping();
                            break;
                        case "DELETEALERTMAPPING":
                            result = DeleteAlertMapping();
                            break;
                        case "SAVEALERTMAPPINGITEM":
                            result = SaveAlertMappingItem();
                            break;
                        case "DELETEALERTMAPPINGITEM":
                            result = DeleteAlertMappingItem();
                            break;
                        case "GETALLALERTMAPPINGDATASOURCE":
                            result = GetAllAlertMappingDataSource();
                            break;
                        case "ADDALERTMAPPINGSOURCE":
                            result = AddAlertMappingSource();
                            break;
                        case "GETIMPORTALERTMAPPINGSCOLUMNS":
                            result = GetImportAlertMappingsColumns();
                            break;
                        case "IMPORTALERTMAPPINGS":
                            result = ImportAlertMappings();
                            break;
                        case "GETALERTMAPPINGDEFAULTCATEGORY":
                            result = GetAlertMappingDefaultCategory();
                            break;
                        case "SETALERTMAPPINGDEFAULTCATEGORY":
                            result = SetAlertMappingDefaultCategory();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "AlertsBasePage", ex.Message, ex.ToString());
                throw ex;
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }


        #region Alert Mappings
        private object GetAlertMappings()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    var searchtxt = HttpUtility.HtmlDecode(clientdata);

                    AlertMappingInfo[] mappings = CreateClient<AlertProvider>().GetAlertMappings(SystemParams.CompanyID, searchtxt, true);
                    if (mappings == null || mappings.Length == 0)
                        return new AlertMappingInfo[0];

                    return mappings;
                }
                else
                    return new AlertMappingInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object SaveAlertMapping()
        {
            try
            {
                LoginSession se = GetCurrentLoginSession();
                if (se != null)
                {
                    var clientdata = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    AlertMappingInfo ami = JsonConvert.DeserializeObject<AlertMappingInfo>(clientdata);
                    long id = CreateClient<AlertProvider>().SaveAlertMapping(SystemParams.CompanyID, ami);

                    return id;
                }
                else
                    return "Failed";
            }
            catch (Foresight.Standard.BusinessException ex)
            {
                return -1;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private string DeleteAlertMapping()
        {
            try
            {
                LoginSession se = GetCurrentLoginSession();
                if (se != null)
                {
                    var clientdata = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    CreateClient<AlertProvider>().DeleteAlertMapping(SystemParams.CompanyID, Convert.ToInt64(clientdata));

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

        private object SaveAlertMappingItem()
        {
            try
            {
                LoginSession se = GetCurrentLoginSession();
                if (se != null)
                {
                    var clientdata = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    AlertMappingItem ami = JsonConvert.DeserializeObject<AlertMappingItem>(clientdata);
                    long itemid = CreateClient<AlertProvider>().SaveAlertMappingItem(SystemParams.CompanyID, ami);

                    return itemid;
                }
                else
                    return "Failed";
            }
            catch (Foresight.Standard.BusinessException ex)
            {
                return -1;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private string DeleteAlertMappingItem()
        {
            try
            {
                LoginSession se = GetCurrentLoginSession();
                if (se != null)
                {
                    var clientdata = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    CreateClient<AlertProvider>().DeleteAlertMappingItem(SystemParams.CompanyID, Convert.ToInt64(clientdata));

                    return "";
                }
                else
                    return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object AddAlertMappingSource()
        {
            try
            {
                LoginSession se = GetCurrentLoginSession();
                if (se != null)
                {
                    var clientdata = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    AlertMappingSourceInfo source = JsonConvert.DeserializeObject<AlertMappingSourceInfo>(clientdata);
                    long id = CreateClient<AlertProvider>().AddAlertMappingSource(SystemParams.CompanyID, source);

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

        private object GetAlertMappingDefaultCategory()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    return SystemParams.GetStringParam(SystemParams.AlertMappingDefaultCategory);
                }
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object SetAlertMappingDefaultCategory()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Form["ClientData"];
                    clientdata = HttpUtility.HtmlDecode(clientdata);

                    SystemParams.SetStringParam(SystemParams.AlertMappingDefaultCategory, clientdata);

                    return "";
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetAllAlertMappingDataSource()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var ap = CreateClient<AssetClassProvider>();
                    AssetMake[] makes = ap.GetAssetMakes("");
                    AssetModel[] models = ap.GetAssetModels(-1, "");
                    StringBuilder sbmake = new StringBuilder();
                    foreach (var m in makes)
                    {
                        sbmake.Append(SPLIT_CHAR180 + m.ID.ToString() + SPLIT_CHAR175 + m.Name);
                    }
                    if (sbmake.Length > 0)
                        sbmake = sbmake.Remove(0, 1);

                    StringBuilder sbmodel = new StringBuilder();
                    foreach (var m in models)
                    {
                        sbmodel.Append(SPLIT_CHAR180 + m.ID.ToString() + SPLIT_CHAR175 + m.Name + SPLIT_CHAR175 + m.MakeId);
                    }
                    if (sbmodel.Length > 0)
                        sbmodel = sbmodel.Remove(0, 1);


                    AlertMappingSourceInfo[] amsources = CreateClient<AlertProvider>().GetAlertMappingSource(SystemParams.CompanyID, -1);
                    AlertMappingSourceInfo[] descs = amsources.Where(d => d.Type == 1).OrderBy(d => d.Value).ToArray();
                    AlertMappingSourceInfo[] categories = amsources.Where(d => d.Type == 2).OrderBy(c => c.Value).ToArray();
                    StringBuilder sbdescs = new StringBuilder();
                    foreach (var d in descs)
                    {
                        sbdescs.Append(SPLIT_CHAR180 + d.ToString());
                    }
                    if (sbdescs.Length > 0)
                        sbdescs = sbdescs.Remove(0, 1);

                    StringBuilder sbcategorys = new StringBuilder();
                    foreach (var c in categories)
                    {
                        sbcategorys.Append(SPLIT_CHAR180 + c.ToString());
                    }
                    if (sbcategorys.Length > 0)
                        sbcategorys = sbcategorys.Remove(0, 1);

                    return new
                    {
                        Makes = sbmake.ToString(),
                        Models = sbmodel.ToString(),
                        Descriptions = sbdescs.ToString(),
                        Categories = sbcategorys.ToString()
                    };
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private object GetImportAlertMappingsColumns()
        {
            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 ImportFromExcel().LoadExcelColumnHead(iconfilebyte);
                        if (columns != null && columns.Length > 0)
                            return columns;
                    }
                }
                return new string[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public class ImportResult
        {
            public int Count = -1;
            public List<AlertMappingClient> Datas = new List<AlertMappingClient>();
        }

        private object ImportAlertMappings()
        {
            try
            {
                int count = 0;
                var session = GetCurrentLoginSession();
                ImportResult result = new ImportResult();
                if (session != null)
                {
                    string p = HttpUtility.HtmlDecode(Request.Form["ClientData"]);
                    bool getData = Convert.ToBoolean(HttpUtility.HtmlDecode(Request.Form["Get"]));
                    string selected = HttpUtility.HtmlDecode(Request.Form["SelectedData"]);
                    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)
                    {
                        if (!CheckRight(SystemParams.CompanyID, Feature.ALERTS_MANAGEMENT))
                            return 0;
                        DataTable dt = new ImportFromExcel().LoadExcelData(iconfilebyte);

                        if (dt != null && dt.Rows.Count > 0)
                        {
                            List<string> sels = new List<string>();
                            if (!string.IsNullOrEmpty(selected))
                            {
                                string[] ss = selected.Split(',');
                                sels = ss.ToList();
                            }
                            int index = 0;
                            AlertProvider client = CreateClient<AlertProvider>();
                            string[] alerttypes = new string[] { "", "Red", "Yellow", "Info" };
                            var ap = CreateClient<AssetClassProvider>();
                            AssetMake[] makes = ap.GetAssetMakes("");
                            List<AssetMake> tempmakes = new List<AssetMake>();
                            tempmakes.Add(new AssetMake() { ID = -1, Name = "(All)" });
                            tempmakes.AddRange(makes);
                            makes = tempmakes.ToArray();

                            AssetModel[] models = ap.GetAssetModels(-1, "");
                            List<AssetModel> tempmodels = new List<AssetModel>();
                            tempmodels.Add(new AssetModel() { ID = -1, Name = "(All)", MakeId = -1 });
                            tempmodels.AddRange(models);
                            models = tempmodels.ToArray();

                            AlertMappingInfo[] allmappings = client.GetAlertMappings(SystemParams.CompanyID, string.Empty, true);
                            var sources = client.GetAlertMappingSource(SystemParams.CompanyID, -1);
                            List<AlertMappingSourceInfo> all_source = new List<AlertMappingSourceInfo>();
                            all_source.AddRange(sources);
                            foreach (DataRow dr in dt.Rows)
                            {
                                if (!getData && sels.Count > 0 && sels.Count >= index + 1 && (sels[index] == "false"))
                                {
                                    index++;
                                    continue;
                                }
                                index++;
                                AlertMappingClient mappinginfo = null;
                                try
                                {
                                    mappinginfo = ConvertToImportAlertMappingInfo(dr, kvs, makes, models);
                                    if (!getData)
                                    {
                                        if (allmappings == null || allmappings.Length == 0)
                                        {
                                            result.Datas.Add(mappinginfo);
                                            continue;
                                        }
                                        if (string.IsNullOrEmpty(mappinginfo.Source) || string.IsNullOrEmpty(mappinginfo.Description))
                                        {
                                            result.Datas.Add(mappinginfo);
                                            continue;
                                        }

                                        if (mappinginfo.Make >= -1 && mappinginfo.Models != null && mappinginfo.Models.Length > 0)
                                        {
                                            if (!alerttypes.Contains(mappinginfo.AlertType))
                                            {
                                                result.Datas.Add(mappinginfo);
                                                continue;
                                            }

                                            AlertMappingInfo ami = allmappings.FirstOrDefault(m => string.Compare(m.Source, mappinginfo.Source, true) == 0
                                            && string.Compare(m.SPN, mappinginfo.SPN, true) == 0 && string.Compare(m.FMI, mappinginfo.FMI, true) == 0
                                            && string.Compare(m.Description.Replace("\r", "").Replace("\n", ""), mappinginfo.Description.Replace("\r", "").Replace("\n", ""), true) == 0);
                                            if (ami == null)
                                            {
                                                result.Datas.Add(mappinginfo);
                                                continue;
                                            }
                                            else
                                            {
                                                if (ami.Items == null || ami.Items.Count == 0)
                                                {
                                                    result.Datas.Add(mappinginfo);
                                                    continue;
                                                }
                                                else
                                                {
                                                    string new_modelstr = string.Join(",", mappinginfo.Models.OrderBy(m => m));
                                                    AlertMappingItem[] mitems = ami.Items.Where(m => m.Make == mappinginfo.Make).ToArray();
                                                    AlertMappingItem newitem = null;
                                                    foreach (AlertMappingItem item in mitems)
                                                    {
                                                        string old_modelstr = string.Join(",", item.Models.OrderBy(m => m));
                                                        if (string.Compare(new_modelstr, old_modelstr, true) == 0)
                                                        {
                                                            newitem = item;
                                                            break;
                                                        }
                                                    }

                                                    if (newitem == null)
                                                    {
                                                        result.Datas.Add(mappinginfo);
                                                        continue;
                                                    }
                                                    else
                                                    {
                                                        newitem.AlertType = mappinginfo.AlertType;
                                                        newitem.Category = mappinginfo.Category;
                                                        AddAlertMappingItem(client, all_source, newitem);
                                                    }
                                                }
                                            }
                                        }

                                        count++;
                                    }
                                    else
                                    {
                                        result.Datas.Add(mappinginfo);
                                    }
                                }
                                catch (Exception e)
                                {
                                    if (mappinginfo != null)
                                    {
                                        result.Datas.Add(mappinginfo);
                                    }
                                }
                            }

                        }
                    }
                    if (!getData)
                    {
                        result.Count = count;
                    }
                }

                return JsonConvert.SerializeObject(result);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private void AddAlertMappingItem(AlertProvider client, List<AlertMappingSourceInfo> all_source, AlertMappingItem item)
        {
            if (!string.IsNullOrWhiteSpace(item.Category))
            {
                AlertMappingSourceInfo oldsource = all_source.FirstOrDefault(m => m.Type == 2 && string.Compare(m.Value, item.Category, true) == 0);
                if (oldsource == null)
                {
                    AlertMappingSourceInfo newsource = new AlertMappingSourceInfo();
                    newsource.Type = 2;
                    newsource.Value = item.Category;
                    newsource.Id = client.AddAlertMappingSource(SystemParams.CompanyID, newsource);
                    all_source.Add(newsource);
                    item.CategoryId = newsource.Id;
                }
                else
                    item.CategoryId = oldsource.Id;
            }
            else
            {
                item.CategoryId = -1;
            }

            item.Id = client.SaveAlertMappingItem(SystemParams.CompanyID, item);
        }

        private AlertMappingClient ConvertToImportAlertMappingInfo(DataRow dr, StringKeyValue[] kvs, AssetMake[] makes, AssetModel[] models)
        {
            AlertMappingClient mapping = new AlertMappingClient();
            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;
                }
                if (string.Compare(kv.Key, "Source", true) == 0)
                {
                    string s = dr[kv.Value].ToString().Trim();
                    mapping.Source = s;
                }
                if (string.Compare(kv.Key, "SPN", true) == 0)
                {
                    string s = dr[kv.Value].ToString().Trim();
                    mapping.SPN = s;
                }
                if (string.Compare(kv.Key, "FMI", true) == 0)
                {
                    string s = dr[kv.Value].ToString().Trim();
                    mapping.FMI = s;
                }
                else if (string.Compare(kv.Key, "Description", true) == 0)
                {
                    mapping.Description = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "Make", true) == 0)
                {
                    string s = dr[kv.Value].ToString().Trim();
                    mapping.MakeName = s;
                    if (!string.IsNullOrWhiteSpace(s))
                    {
                        if (string.Compare("(All)", s, true) == 0)
                            mapping.Make = -1;
                        else
                        {
                            AssetMake make = makes.FirstOrDefault(m => string.Compare(m.Name, s, true) == 0);
                            if (make != null)
                                mapping.Make = make.ID;
                        }
                    }
                }
                else if (string.Compare(kv.Key, "Models", true) == 0)
                {
                    string s = dr[kv.Value].ToString().Trim();
                    if (!string.IsNullOrWhiteSpace(s))
                    {
                        mapping.ModelNames = s;
                        string[] modelsstr = s.Split(',');
                        if (modelsstr != null && modelsstr.Length > 0)
                        {
                            List<int> lsmodel = new List<int>();
                            foreach (string str in modelsstr)
                            {
                                if (!string.IsNullOrWhiteSpace(str))
                                {
                                    if (string.Compare("(All)", str, true) == 0)
                                        lsmodel.Add(-1);
                                    else
                                    {
                                        AssetModel model = models.FirstOrDefault(m => mapping.Make == m.MakeId && string.Compare(m.Name, str, true) == 0);
                                        if (model != null)
                                            lsmodel.Add(model.ID);
                                    }
                                }
                            }
                            mapping.Models = lsmodel.ToArray();
                        }
                    }
                }
                else if (string.Compare(kv.Key, "AlertType", true) == 0)
                {
                    mapping.AlertType = dr[kv.Value].ToString().Trim();
                }
                else if (string.Compare(kv.Key, "Category", true) == 0)
                {
                    mapping.Category = dr[kv.Value].ToString().Trim();
                }
            }
            return mapping;
        }


        #endregion

        private object GetAlerts()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Context.Request.Params["ClientData"];
                    AlertQueryParams alertparam = JsonConvert.DeserializeObject<AlertQueryParams>(clientdata);
                    DateTime beginDate = Helper.DBMinDateTime;
                    DateTime endDate = DateTime.MaxValue;
                    if (!DateTime.TryParse(alertparam.BeginDate, out beginDate))
                        beginDate = Helper.DBMinDateTime;
                    //else
                    //    beginDate = beginDate.ToUniversalTime();
                    if (!DateTime.TryParse(alertparam.EndDate, out endDate))
                        endDate = DateTime.MaxValue;

                    int assigned = -1;
                    int completed = -1;
                    if (alertparam.AlertStatus != null && alertparam.AlertStatus.Length > 0)
                    {
                        if (alertparam.AlertStatus.Contains("Unassigned") && !alertparam.AlertStatus.Contains("Assigned"))
                            assigned = 0;
                        if (!alertparam.AlertStatus.Contains("Unassigned") && alertparam.AlertStatus.Contains("Assigned"))
                            assigned = 1;

                        if (alertparam.AlertStatus.Contains("Completed") && !alertparam.AlertStatus.Contains("Uncompleted"))
                            completed = 1;
                        if (!alertparam.AlertStatus.Contains("Completed") && alertparam.AlertStatus.Contains("Uncompleted"))
                            completed = 0;
                    }
                    alertparam.SearchText = HttpUtility.HtmlDecode(alertparam.SearchText);

                    AssetAlertGridViewItem[] assetalerts = null;
                    if (alertparam.AssetID > 0)
                        assetalerts = CreateClient<WorkOrderProvider>().GetAssetAlertGridViewItemsByAsset(SystemParams.CompanyID, alertparam.AssetID, beginDate, endDate, alertparam.AlertTypes, alertparam.JobSites, assigned, completed, alertparam.SearchText, alertparam.IncludeunCompleted, alertparam.Category);
                    else
                        assetalerts = CreateClient<AlertProvider>().GetAssetAlertGridViewItems(SystemParams.CompanyID, beginDate, endDate, alertparam.AlertTypes, alertparam.AssetGroups, alertparam.JobSites, assigned, completed, alertparam.SearchText, session.User.UID, alertparam.IncludeunCompleted, alertparam.Category);

                    if (assetalerts == null || assetalerts.Length == 0)
                        return string.Empty;

                    StringBuilder sb = new StringBuilder();
                    foreach (AssetAlertGridViewItem item in assetalerts)
                    {
                        AlertInfo ai = ConvertAlertObj(item);

                        sb.Append(SPLIT_CHAR180 + ai.ToString());
                    }
                    if (sb.Length > 0)
                    {
                        return sb.ToString().Substring(1);
                    }
                    return string.Empty;
                }
                else
                    return string.Empty;
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAlerts", ex.Message, ex.ToString());
                return new string[] { ex.Message };
            }
        }

        private object GetMachineAlerts()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Context.Request.Params["ClientData"];
                    AlertQueryParams alertparam = JsonConvert.DeserializeObject<AlertQueryParams>(clientdata);
                    DateTime beginDate = Helper.DBMinDateTime;
                    DateTime endDate = DateTime.MaxValue;
                    if (!DateTime.TryParse(alertparam.BeginDate, out beginDate))
                        beginDate = Helper.DBMinDateTime;
                    //else
                    //    beginDate = beginDate.ToUniversalTime();
                    if (!DateTime.TryParse(alertparam.EndDate, out endDate))
                        endDate = DateTime.MaxValue;


                    int assigned = -1;
                    int completed = -1;
                    if (alertparam.AlertStatus != null && alertparam.AlertStatus.Length > 0)
                    {
                        if (alertparam.AlertStatus.Contains("Unassigned") && !alertparam.AlertStatus.Contains("Assigned"))
                            assigned = 0;
                        if (!alertparam.AlertStatus.Contains("Unassigned") && alertparam.AlertStatus.Contains("Assigned"))
                            assigned = 1;

                        if (alertparam.AlertStatus.Contains("Completed") && !alertparam.AlertStatus.Contains("Uncompleted"))
                            completed = 1;
                        if (!alertparam.AlertStatus.Contains("Completed") && alertparam.AlertStatus.Contains("Uncompleted"))
                            completed = 0;
                    }
                    alertparam.SearchText = HttpUtility.HtmlDecode(alertparam.SearchText);

                    AssetAlertGridViewItem[] assetalerts = null;
                    if (alertparam.AssetID > 0)
                        assetalerts = CreateClient<WorkOrderProvider>().GetAssetAlertGridViewItemsByAsset(SystemParams.CompanyID, alertparam.AssetID, beginDate, endDate, alertparam.AlertTypes, alertparam.JobSites, assigned, completed, alertparam.SearchText, alertparam.IncludeunCompleted, alertparam.Category);
                    else
                        assetalerts = CreateClient<AlertProvider>().GetAssetAlertGridViewItems(SystemParams.CompanyID, beginDate, endDate, alertparam.AlertTypes, alertparam.AssetGroups, alertparam.JobSites, assigned, completed, alertparam.SearchText, session.User.UID, alertparam.IncludeunCompleted, alertparam.Category);

                    if (assetalerts == null || assetalerts.Length == 0)
                        return string.Empty;

                    List<MachineInfoForAlert> machinealerts = new List<MachineInfoForAlert>();
                    foreach (AssetAlertGridViewItem item in assetalerts)
                    {
                        AlertInfo ai = ConvertAlertObj(item);
                        MachineInfoForAlert mi = machinealerts.FirstOrDefault((i) => i.MachineID == ai.MachineID);
                        if (mi == null)
                        {
                            mi = new MachineInfoForAlert();
                            mi.MachineID = ai.MachineID;
                            mi.MachineName = ai.MachineName;
                            mi.VIN = ai.VIN;
                            mi.Make = ai.Make;
                            mi.Model = ai.Model;
                            mi.EngineHours = ai.CurrentHours;
                            mi.OpenWorkOrders = ai.OpenWorkOrderCount;

                            machinealerts.Add(mi);
                        }
                        mi.Alerts.Add(ai);

                        int count = ai.RepeatedAlerts.Count + 1;

                        if (ai.AlertType == "Preventative Maintenance"
                          || ai.AlertType == "PM_ALERT" || ai.AlertType == "TBM_ALERT" || ai.AlertType == "HM_ALERT"
                          || ai.AlertType == "RDM_ALERT" || ai.AlertType == "ADM_ALERT")
                            mi.PMAlertCount += count;
                        else if (INSPECT.Contains(ai.AlertType, StringComparer.OrdinalIgnoreCase))
                            mi.InspectAlertCount += count;
                        else
                            mi.DTCAlertCount += count;
                        if (ai.AlertLocalTime > mi.LatestAlertDateTime)
                            mi.LatestAlertDateTime = ai.AlertLocalTime;
                    }

                    StringBuilder sb = new StringBuilder();
                    foreach (MachineInfoForAlert mi in machinealerts)
                    {
                        sb.Append(SPLIT_CHAR183 + mi.ToString());
                    }
                    if (sb.Length > 0)
                    {
                        return sb.ToString().Substring(1);
                    }
                    return string.Empty;
                }
                else
                    return string.Empty;
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAlerts", ex.Message, ex.ToString());
                return new string[] { ex.Message };
            }
        }

        private object GetPMAlertServiceDescriptions()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Context.Request.Params["ClientData"];
                    long[] alertids = JsonConvert.DeserializeObject<long[]>(clientdata);

                    return CreateClient<AlertProvider>().GetAlertServiceDescriptions(SystemParams.CompanyID, alertids);
                }
                return null;
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetPMAlertServiceDescriptions", ex.Message, ex.ToString());
                return ex.Message;
            }
        }
        private AlertInfo ConvertAlertObj1(AssetAlertItem item)
        {
            AlertInfo ai = new AlertInfo();
            ai.AlertID = item.ID;
            ai.AlertType = item.AlertType;
            ai.AlertLocalTime = item.AlertLocalTime;
            ai.Completed = item.Completed;
            ai.MachineID = item.AssetID;
            ai.Model = item.ModelName;
            ai.Make = item.MakeName;
            ai.VIN = item.VIN;
            ai.MachineName = item.AssetName;
            ai.EngineHours = item.EngineHours;
            ai.Description = item.Description;
            ai.Description = ai.FormatDescription(ai.Description);
            ai.ServiceDescription = item.ServiceDescription;
            ai.RepeatedAlerts = item.RepeatedAlerts;
            ai.AlertCount = item.RepeatedAlerts.Count + 1;
            ai.ScheduleID = item.ScheduleID;
            ai.IntervalID = item.IntervalID;
            ai.Recurring = item.Recurring;
            ai.Priority = item.Priority;
            ai.ExpectedCost = item.ExpectedCost;

            return ai;
        }

        private AlertInfo ConvertAlertObj(AssetAlertGridViewItem item)
        {
            AlertInfo ai = new AlertInfo();
            ai.AlertID = item.ID;
            ai.WorkOrderID = item.WorkOrderId;
            ai.WorkOrderStatus = item.WorkOrderStatus;
            ai.AlertType = item.AlertType;
            ai.AlertTime_UTC = item.LastAlertTime;
            ai.AlertLocalTime = item.AlertLocalTime;
            ai.Completed = item.Completed;
            ai.MachineID = item.AssetID;
            //ai.ModelID = item.ModelName;
            ai.Model = item.ModelName;
            //ai.MakeID = item.MakeName;
            ai.Make = item.MakeName;
            ai.VIN = item.VIN;
            ai.MachineName = item.AssetName;
            ai.EngineHours = item.EngineHours;
            ai.CurrentHours = item.CurrentEngineHours;
            ai.Description = item.Description;
            ai.Description = ai.FormatDescription(ai.Description);
            //ai.ServiceDescription = item.ServiceDescription;
            ai.RepeatedAlerts = item.RepeatedAlerts;
            ai.AlertCount = item.RepeatedAlerts.Count + 1;
            ai.OpenWorkOrderCount = item.OpenWorkOrderCount;
            //ai.ScheduleID = item.ScheduleID;
            //ai.IntervalID = item.IntervalID;
            //ai.Recurring = item.Recurring;
            //ai.Priority = item.Priority;
            //ai.ExpectedCost = item.ExpectedCost;

            return ai;
        }
        private AlertInfo ConvertAlertObj2(AcknowledgedAlertItem item)
        {
            AlertInfo ai = new AlertInfo();
            ai.AlertID = item.ID;
            ai.WorkOrderID = item.WorkOrderId;
            ai.AlertType = item.AlertType;
            ai.AlertTime_UTC = item.LastAlertTime;
            ai.AlertLocalTime = item.AlertLocalTime;
            ai.MachineID = item.AssetID;
            ai.Model = item.ModelName;
            ai.Make = item.MakeName;
            ai.VIN = item.VIN;
            ai.MachineName = item.AssetName;
            ai.EngineHours = item.EngineHours;
            ai.Description = item.Description;
            ai.Description = ai.FormatDescription(ai.Description);
            ai.RepeatedAlerts = item.RepeatedAlerts;
            ai.AlertCount = item.RepeatedAlerts.Count + 1;
            ai.OpenWorkOrderCount = item.OpenWorkOrderCount;
            ai.AcknowledgedByName = item.AcknowledgedBy;
            ai.AcknowledgedTime_UTC = item.AcknowledgedTime;
            ai.AcknowledgedTime_Local = item.AcknowledgedLocalTime;
            ai.AcknowledgedComment = item.AcknowledgedComment;

            return ai;
        }

        private object GetAcknowledgedAlerts()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Context.Request.Params["ClientData"];
                    AlertQueryParams alertparam = JsonConvert.DeserializeObject<AlertQueryParams>(clientdata);
                    DateTime beginDate = Helper.DBMinDateTime;
                    DateTime endDate = DateTime.MaxValue;
                    if (!DateTime.TryParse(alertparam.BeginDate, out beginDate))
                        beginDate = Helper.DBMinDateTime;
                    //else
                    //    beginDate = beginDate.ToUniversalTime();
                    if (!DateTime.TryParse(alertparam.EndDate, out endDate))
                        endDate = DateTime.MaxValue;

                    alertparam.SearchText = HttpUtility.HtmlDecode(alertparam.SearchText);
                    alertparam.AlertStatus = new string[0];
                    AcknowledgedAlertItem[] ackalerts = CreateClient<AlertProvider>().GetAcknowledgedAlerts(SystemParams.CompanyID, beginDate, endDate, alertparam.AlertTypes, alertparam.AssetGroups, alertparam.SearchText);
                    if (ackalerts == null || ackalerts.Length == 0)
                        return string.Empty;

                    if (alertparam.AssetID > 0)
                        ackalerts = ackalerts.Where(m => m.AssetID == alertparam.AssetID).ToArray();

                    if (ackalerts == null || ackalerts.Length == 0)
                        return string.Empty;

                    StringBuilder sb = new StringBuilder();
                    foreach (AcknowledgedAlertItem item in ackalerts)
                    {
                        AlertInfo ai = ConvertAlertObj2(item);
                        sb.Append(SPLIT_CHAR180 + ai.ToString());
                    }
                    if (sb.Length > 0)
                    {
                        return sb.ToString().Substring(1);
                    }

                    return string.Empty;
                }
                else
                    return string.Empty;
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAcknowledgedAlerts", ex.Message, ex.ToString());
                return new string[] { ex.Message };
            }
        }

        private object GetAlertsLisence()
        {
            try
            {
                AlertsLisenceItem result = new AlertsLisenceItem();
                if (GetCurrentLoginSession() != null)
                {
                    Foresight.Fleet.Services.Customer.LicenseInfo license = SystemParams.GetLicense();
                    if (license != null && license.Items.Count > 0)
                    {
                        var woitem = license.Items.FirstOrDefault(m => m.Key == "WorkOrder");
                        if (woitem != null && Helper.IsTrue(woitem.Value))
                            result.WorkOrder = true;
                    }
                    result.AcknowledgingAlerts = Helper.IsTrue(SystemParams.GetStringParam("AcknowledgingAlerts"));
                }
                return result;
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAlertsLisence", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private string SaveAcknowledgeAlert()
        {
            try
            {
                LoginSession se = GetCurrentLoginSession();
                if (se != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var ids = HttpUtility.HtmlDecode(clientdata[0]);
                    var acknowledgmentcomment = HttpUtility.HtmlDecode(clientdata[1]);
                    long[] list = JsonConvert.DeserializeObject<long[]>(ids);
                    AlertManager am = new AlertManager(SystemParams.DataDbConnectionString);
                    am.AcknowledgeAlert(se.User.UID, list, acknowledgmentcomment);
                    return "OK";
                }
                else
                    return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private string AssignedAlertsToWorkOrder()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var clientdata = Request.Form["ClientData"].Split((char)170);
                    var id = HttpUtility.HtmlDecode(clientdata[0]);
                    var ids = HttpUtility.HtmlDecode(clientdata[1]);
                    long workorderid = Convert.ToInt64(id);
                    long[] alertids = JsonConvert.DeserializeObject<long[]>(ids);
                    if (alertids == null)
                        alertids = new long[0];

                    var wp = CreateClient<WorkOrderProvider>();
                    var existsalerts = wp.GetWorkOrderAlerts(SystemParams.CompanyID, workorderid).Select(a => a.ID);
                    var added = alertids.Except(existsalerts).ToArray();
                    var deleted = existsalerts.Except(alertids).ToArray();
                    if (added.Length > 0)
                        wp.AddOrRemoveAlertsFromWorkOrder(SystemParams.CompanyID, workorderid, added, true);
                    if (deleted.Length > 0)
                        wp.AddOrRemoveAlertsFromWorkOrder(SystemParams.CompanyID, workorderid, deleted, false);
                    return "OK";
                }
                else
                    return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

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

                    long workorderid = 0;
                    long.TryParse(clientdata, out workorderid);

                    AlertItems items = WorkOrderManager.GetWorkOrderAlerts(workorderid, session.SessionID);
                    if (items == null)
                        return new AlertItems();

                    return new
                    {
                        WorkOrderID = workorderid,
                        Data = items
                    };
                }
                else
                    return new
                    {
                        WorkOrderID = -1,
                        Data = new AlertItems()
                    };
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetWorkOrderAlerts", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

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

                    long machineid = 0;
                    long.TryParse(mid, out machineid);

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

                    AssetAlertItem[] alerts = CreateClient<WorkOrderProvider>().GetNoneAssignedAlerts(SystemParams.CompanyID, machineid);
                    //AssetAlertGridViewItem[] alerts = CreateClient<WorkOrderProvider>().GetAssetAlertGridViewItemsByAsset(SystemParams.CompanyID, machineid, Helper.DBMinDateTime, DateTime.MaxValue, null, null, -1, -1, "", false);
                    AlertItems items = new AlertItems();
                    if (alerts != null)
                    {
                        var dtcalerts = new List<AlertInfo>();
                        var pmaalerts = new List<AlertInfo>();
                        var inspectalerts = new List<AlertInfo>();
                        var oilalerts = new List<AlertInfo>();
                        Dictionary<string, List<AlertInfo>> pmalertdic = new Dictionary<string, List<AlertInfo>>();
                        foreach (var alertitem in alerts.OrderByDescending(ai => ai.AlertTime))
                        {
                            if (alertids != null && alertids.Length > 0 && !alertids.Contains(alertitem.ID))
                                continue;

                            List<AlertInfo> tempList = null;
                            var category = DetermineAlertCategory(alertitem.AlertType);
                            if (category == AssetAlertCategory.PMAlert)
                                tempList = pmaalerts;
                            else if (category == AssetAlertCategory.InspectAlert)
                                tempList = inspectalerts;
                            else if (category == AssetAlertCategory.OilSampleAlert)
                                tempList = oilalerts;
                            else
                                tempList = dtcalerts;

                            var a = ConvertAlertObj1(alertitem);
                            a.RepeatedAlerts = alertitem.RepeatedAlerts;
                            a.AlertCount = alertitem.RepeatedAlerts.Count + 1;
                            tempList.Add(a);

                            if (category == AssetAlertCategory.PMAlert)
                            {
                                if (!pmalertdic.ContainsKey(a.ScheduleID))
                                    pmalertdic[a.ScheduleID] = new List<AlertInfo>();
                                pmalertdic[a.ScheduleID].Add(a);
                            }
                        }
                        items.DTCAlerts = dtcalerts.ToArray();
                        items.PMAlerts = pmaalerts.ToArray();
                        items.InspectAlerts = inspectalerts.ToArray();
                        items.OilAlerts = oilalerts.ToArray();
                        items.AllExpectedCost = 0;

                        foreach (var dic in pmalertdic)
                        {
                            items.AllExpectedCost += dic.Value.Where(m => !m.Recurring).Sum(m => m.ExpectedCost);

                            int minPriority = dic.Value.Select(m => m.Priority).Min();
                            var recalerts = dic.Value.Where(m => m.Priority == minPriority && m.Recurring && m.ExpectedCost > 0);
                            if (recalerts != null && recalerts.Count() > 0)
                                items.AllExpectedCost += recalerts.Sum(m => m.ExpectedCost);
                        }
                    }
                    return new
                    {
                        MachineID = machineid,
                        Data = items
                    };
                }
                else
                    return new
                    {
                        MachineID = -1,
                        Data = new AlertInfo[0]
                    };
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAssetAlerts", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private string SaveAutoAcknowledgeAlertTypes()
        {
            try
            {
                LoginSession session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    string[] alerttypes = JsonConvert.DeserializeObject<string[]>(clientdata);
                    CreateClient<WorkOrderProvider>().SaveAutoAcknowledgeAlertTypes(SystemParams.CompanyID, alerttypes, session.User.UID);

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

        private object GetAutoAcknowledgeAlertTypes()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string[] alerttypes = CreateClient<WorkOrderProvider>().GetAutoAcknowledgeAlertTypes(SystemParams.CompanyID, GetCurrentLoginSession().User.UID);
                    return alerttypes;
                }
                else
                    return new string[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAutoAcknowledgeAlertTypes", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetAutoAcknowledgeAlertTypesHistory()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    AutoAcknowledgeItem[] items = CreateClient<WorkOrderProvider>().GetAutoAcknowledgeAlertTypesHistory(SystemParams.CompanyID, GetCurrentLoginSession().User.UID);
                    if (items == null || items.Length == 0)
                        return new AutoAcknowledgeInfo[0];

                    List<AutoAcknowledgeInfo> ls = new List<AutoAcknowledgeInfo>();
                    foreach (AutoAcknowledgeItem item in items)
                    {
                        AutoAcknowledgeInfo ai = new AutoAcknowledgeInfo();
                        Helper.CloneProperty(ai, item);
                        ai.LocalUpdatedOn = ai.UpdatedOnLocal;
                        ls.Add(ai);
                    }
                    return ls.OrderBy(m => m.LocalUpdatedOn).ToArray();
                }
                else
                    return new AutoAcknowledgeInfo[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAutoAcknowledgeAlertTypesHistory", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private static readonly string[] PMALERTS = new string[] { "Preventative Maintenance" };
        private static readonly string[] INSPECT = new string[] { "Red-Inspect", "Yellow-Inspect", "Green-Inspect", "Info-Inspect" };
        private static readonly string[] OILSAMPLE = new string[] { "Oil Sample Result" };
        private static AssetAlertCategory DetermineAlertCategory(string alerttype)
        {
            if (PMALERTS.Contains(alerttype, StringComparer.OrdinalIgnoreCase))
            {
                return AssetAlertCategory.PMAlert;
            }
            if (INSPECT.Contains(alerttype, StringComparer.OrdinalIgnoreCase))
            {
                return AssetAlertCategory.InspectAlert;
            }
            if (OILSAMPLE.Contains(alerttype, StringComparer.OrdinalIgnoreCase))
            {
                return AssetAlertCategory.OilSampleAlert;
            }

            return AssetAlertCategory.DTCAlert;
        }

        private object GetAssetGroups()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var groups = MachineManagement.GetMachineGroupsByUser(session.User.UID, null);
                    List<StringKeyValue> list = new List<StringKeyValue>();
                    foreach (var gp in groups)
                    {
                        StringKeyValue kv = new StringKeyValue();
                        kv.Key = gp.GroupID;
                        kv.Value = gp.GroupName;
                        list.Add(kv);
                    }

                    return list.OrderBy((m) => m.Value).ToArray();
                }
                else
                    return new StringKeyValue[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAssetGroups", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetAssignTos()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var users = Users.UserManagement.GetActiveUsers(session.SessionID, SystemParams.CompanyID);
                    List<StringKeyValue> list = new List<StringKeyValue>();
                    foreach (var u in users)
                    {
                        StringKeyValue kv = new StringKeyValue();
                        kv.Key = u.IID;
                        kv.Value = u.DisplayName;
                        list.Add(kv);
                    }

                    list = list.OrderBy((m) => m.Value).ToList();
                    list.Insert(0, new StringKeyValue() { Key = "1", Value = "Alert Creator" });
                    list.Insert(1, new StringKeyValue() { Key = "2", Value = "First Assigned Contact in Managed Assets" });

                    return list.ToArray();
                }
                else
                    return new StringKeyValue[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAssignTos", ex.Message, ex.ToString());
                return ex.Message;
            }
        }
        private object GetJobsites()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    JobSiteItem[] jss = CreateClient<JobSiteProvider>().GetJobSiteItems(SystemParams.CompanyID, string.Empty, false);
                    List<StringKeyValue> list = new List<StringKeyValue>();
                    foreach (JobSiteItem js in jss)
                    {
                        StringKeyValue kv = new StringKeyValue();
                        kv.Key = js.ID.ToString();
                        kv.Value = js.Name;
                        list.Add(kv);
                    }

                    return list.OrderBy((m) => m.Value).ToArray();
                }
                else
                    return new StringKeyValue[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAssetGroups", ex.Message, ex.ToString());
                return ex.Message;
            }
        }
        private object GetAlertCategory()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    AlertMappingSourceInfo[] sources = CreateClient<AlertProvider>().GetAlertMappingSource(SystemParams.CompanyID, 2);
                    List<StringKeyValue> list = new List<StringKeyValue>();
                    foreach (AlertMappingSourceInfo si in sources)
                    {
                        StringKeyValue kv = new StringKeyValue();
                        kv.Key = si.Id.ToString();
                        kv.Value = si.Value;
                        list.Add(kv);
                    }

                    return list.OrderBy((m) => m.Value).ToArray();
                }
                else
                    return new StringKeyValue[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAlertCategory", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object GetAlertTypes()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    AlertManager am = new AlertManager(SystemParams.DataDbConnectionString);
                    return am.GetAlertTypes(); ;
                }
                else
                    return new StringKeyValue[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetAlertTypes", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        #region Work Order Generators

        private object GetWorkOrderGenerators()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    WorkOrderGeneratorInfo[] generators = CreateClient<WorkOrderProvider>().GetWorkOrderGenerators(SystemParams.CompanyID);
                    if (generators == null)
                        return new WorkOrderGeneratorInfo[0];

                    return generators;
                }
                else
                    return new WorkOrderGeneratorInfo[0];
            }
            catch (Exception ex)
            {
                AddLog("ERROR", "AlertsBasePage.GetWorkOrderGenerators", ex.Message, ex.ToString());
                return ex.Message;
            }
        }

        private object SaveWorkOrderGenerator()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    WorkOrderGeneratorInfo generator = JsonConvert.DeserializeObject<WorkOrderGeneratorInfo>(clientdata);

                    if (generator.Id > 0)
                    {
                        CreateClient<WorkOrderProvider>().UpdateWorkOrderGenerator(SystemParams.CompanyID, generator);
                    }
                    else
                    {
                        generator.Id = CreateClient<WorkOrderProvider>().AddNewWorkOrderGenerator(SystemParams.CompanyID, generator);
                    }

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

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

                    CreateClient<WorkOrderProvider>().DeleteWorkOrderGenerator(SystemParams.CompanyID, Convert.ToInt32(id));

                    return new string[0];
                }
                return "Failed";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }
        #endregion

    }

    public class AlertsLisenceItem
    {
        public bool WorkOrder = false;
        public bool AcknowledgingAlerts = false;
    }
}
