using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services.Inspection;
using Foresight.Fleet.Services.JobSite;
using Foresight.ServiceModel;
using IronIntel.Contractor.FilterQ;
using IronIntel.Contractor.Machines;
using IronIntel.Contractor.Maintenance;
using IronIntel.Contractor.Users;
using IronIntel.Services.Contractor;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace IronIntel.Contractor.Site
{
    public class InspectionBasePage : ContractorBasePage
    {
        protected void ProcessRequest(string method)
        {
            object result = null;
            try
            {
                string methodName = Request.Params["MethodName"];
                if (methodName != null)
                {
                    switch (methodName)
                    {
                        case "GetGlobalSections":
                            result = GetGlobalSections();
                            break;
                        case "GetGlobalQuestions":
                            result = GetGlobalQuestions();
                            break;
                        case "SaveGlobalSection":
                            result = SaveGlobalSection();
                            break;
                        case "SaveGlobalQuestion":
                            result = SaveGlobalQuestion();
                            break;
                        case "DeleteGlobalSection":
                            result = DeleteGlobalSection();
                            break;
                        case "DeleteGlobalQuestion":
                            result = DeleteGlobalQuestion();
                            break;
                        case "GetTemplates":
                            result = GetTemplates();
                            break;
                        case "GetTemplate":
                            result = GetTemplate();
                            break;
                        case "SaveTemplate":
                            result = SaveTemplate();
                            break;
                        case "DeleteTemplate":
                            result = DeleteTemplate();
                            break;
                        case "PublishTemplate":
                            result = PublishTemplate();
                            break;
                        case "GetAssetMakes":
                            result = GetAssetMakes();
                            break;
                        case "GetAssetModels":
                            result = GetAssetModels();
                            break;
                        case "GetAssetTypes":
                            result = GetAssetTypes();
                            break;
                        case "GetInspectItems":
                            result = GetInspectItems();
                            break;
                        case "GetGlobalSectionsByID":
                            result = GetGlobalSectionsByID();
                            break;
                        case "GetInspectionReport":
                            result = GetInspectionReport();
                            break;
                        case "TemplateSaveAs":
                            result = TemplateSaveAs();
                            break;
                        case "GetInspectEmailList":
                            result = GetInspectEmailList();
                            break;
                        case "GetInspectionReportForEdit":
                            result = GetInspectionReportForEdit();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "InspectionBasePage", ex.Message, ex.ToString());
                throw ex;
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }
        protected void ProcessFileRequest()
        {
            bool download = false;
            string fileName = "";
            byte[] buffer = null;
            try
            {
                string type = Request.Params["t"];
                if (type != null)
                {
                    switch (type)
                    {
                        case "1"://download
                            buffer = GetInspectionPDF(out fileName);
                            download = true;
                            break;
                        case "2"://print
                            buffer = GetInspectionPDF(out fileName);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "InspectionBasePage", ex.Message, ex.ToString());
                throw ex;
            }

            fileName = HttpUtility.UrlEncode(string.IsNullOrEmpty(fileName) ? "attachment" : fileName, System.Text.Encoding.UTF8) + ".pdf";

            Response.ContentType = "application/pdf";
            Response.BufferOutput = false;
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.AddHeader("Content-Disposition"
                , string.Format("{0}filename={1}", download ? "attachment;" : "", fileName));
            if (buffer != null)
            {
                Response.AddHeader("Content-Length", buffer.Length.ToString());
                Response.BinaryWrite(buffer);
            }
            Response.Flush();
            Response.End();
        }

        private object GetInspectItems()
        {
            try
            {
                var sesstion = GetCurrentLoginSession();
                if (sesstion != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    DateTime startdate = Helper.DBMinDateTime;
                    DateTime enddate = DateTime.MaxValue;
                    if (!DateTime.TryParse(ps[1], out startdate))
                        startdate = Helper.DBMinDateTime;
                    if (!DateTime.TryParse(ps[2], out enddate))
                        enddate = DateTime.MaxValue;
                    else
                        enddate = enddate.Date.AddDays(1).AddSeconds(-1);

                    startdate = SystemParams.CustomerDetail.CustomerTimeToUtc(startdate);
                    enddate = SystemParams.CustomerDetail.CustomerTimeToUtc(enddate);
                    string filter = HttpUtility.HtmlDecode(ps[3]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        TeamInspectItem[] insplectitems = client.GetInspectItems(SystemParams.CompanyID, startdate, enddate, filter, sesstion.User.UID);
                        if (insplectitems == null || insplectitems.Length == 0)
                            return new TeamInspectInfo[0];

                        List<TeamInspectInfo> list = new List<TeamInspectInfo>();
                        foreach (TeamInspectItem item in insplectitems)
                        {
                            TeamInspectInfo inspect = new TeamInspectInfo();
                            Helper.CloneProperty(inspect, item);
                            list.Add(inspect);
                        }
                        return list.ToArray();
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        AssetInspectItem[] insplectitems = client.GetInspectItems(SystemParams.CompanyID, startdate, enddate, filter, sesstion.User.UID);
                        if (insplectitems == null || insplectitems.Length == 0)
                            return new AssetInspectInfo[0];

                        List<AssetInspectInfo> list = new List<AssetInspectInfo>();
                        foreach (AssetInspectItem item in insplectitems)
                        {
                            AssetInspectInfo inspect = new AssetInspectInfo();
                            Helper.CloneProperty(inspect, item);
                            list.Add(inspect);
                        }
                        return list.ToArray();
                    }

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

        private object GetInspectionReportForEdit()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string id = HttpUtility.HtmlDecode(ps[1]);
                    string companyId = SystemParams.CompanyID;

                    InspectReportInfo report = null;
                    var aic = CreateClient<AssetInspectClient>();
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        report = client.GetInspection(companyId, id);
                    }
                    else
                    {
                        report = aic.GetInspection(companyId, id);
                    }

                    if (report == null)
                        return null;

                    var ir = new InspectReportEditItem();
                    Helper.CloneProperty(ir, report);
                    ir.CommitTime = SystemParams.CustomerDetail.UtcToCustomerTime(ir.CommitTime);
                    ir.Answers.AddRange(report.Answers);
                    ir.Medias.AddRange(report.Medias);
                    if (!teamintelligence)
                    {
                        var aclient = FleetServiceClientHelper.CreateClient<AssetQueryClient>(companyId, session.SessionID);
                        ir.Asset = aclient.GetAssetBasicInfoByID(companyId, ir.AssetId);
                    }
                    // list
                    bool hasAsset = false;
                    bool hasEmail = false;
                    bool hasJobsite = false;
                    foreach (var p in report.Template.Pages)
                    {
                        foreach (var s in p.Sections)
                        {
                            foreach (var q in s.Questions)
                            {
                                if (q.QuestionType == QuestionTypes.DropDown)
                                {
                                    if (q.LookupSource == LookupSources.Assets)
                                    {
                                        hasAsset = true;
                                    }
                                    else if (q.LookupSource == LookupSources.Employee)
                                    {
                                        hasEmail = true;
                                    }
                                    else if (q.LookupSource == LookupSources.Jobsites)
                                    {
                                        hasJobsite = true;
                                    }
                                }
                            }
                        }
                    }
                    if (hasEmail)
                    {
                        ir.EmailList = aic.GetInspectEmailList(companyId, string.Empty);
                    }
                    if (hasAsset)
                    {
                        var ac = CreateClient<AssetQueryClient>();
                        ir.AssetList = ac.GetAssetBasicInfoByUser(companyId, string.Empty, session.User.UID);
                    }
                    if (hasJobsite)
                    {
                        var jc = CreateClient<JobSiteProvider>();
                        ir.JobSiteList = jc.GetJobSiteLimitItems(companyId, string.Empty);
                    }
                    return ir;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetInspectionReport()
        {
            try
            {
                var sesstion = GetCurrentLoginSession();
                if (sesstion != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string id = HttpUtility.HtmlDecode(ps[1]);

                    InspectReportInfo report = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        report = client.GetInspection(SystemParams.CompanyID, id);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        report = client.GetInspection(SystemParams.CompanyID, id);
                    }

                    if (report == null)
                        return null;

                    InspectReportItem ir = new InspectReportItem();
                    Helper.CloneProperty(ir, report);
                    ir.CommitTime = SystemParams.CustomerDetail.UtcToCustomerTime(ir.CommitTime);
                    ir.Answers.AddRange(report.Answers);
                    ir.Medias.AddRange(report.Medias);
                    ir.IdentifiedQuestions = new List<IdentifiedQuestionItem>();
                    foreach (var p in ir.Template.Pages)
                    {
                        foreach (var s in p.Sections)
                        {
                            foreach (var q in s.Questions)
                            {
                                foreach (var a in ir.Answers)
                                {
                                    if (q.Id.Equals(a.QuestionId, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (q.QuestionType == QuestionTypes.Date || q.QuestionType == QuestionTypes.DateAndTime)
                                        {
                                            DateTime dt = DateTime.Now;
                                            if (DateTime.TryParse(a.Result, out dt))
                                            {
                                                if (q.QuestionType == QuestionTypes.Date)
                                                    a.Result = dt.ToString("M/d/yyyy tt");
                                                else if (q.QuestionType == QuestionTypes.DateAndTime)
                                                    a.Result = dt.ToString("M/d/yyyy h:mm:ss tt");
                                            }
                                        }
                                        else if (q.QuestionType == QuestionTypes.Number
                                            || q.QuestionType == QuestionTypes.Integer
                                            || q.QuestionType == QuestionTypes.EngingHours
                                            || q.QuestionType == QuestionTypes.Odometer)
                                        {
                                            double tn = 0;
                                            if (double.TryParse(a.Result, out tn))
                                                a.Result = tn.ToString("#,##0.##");
                                        }

                                        //IdentifiedQuestion
                                        if (q.QuestionType != QuestionTypes.DropDown
                                             && q.QuestionType != QuestionTypes.YesOrNo
                                             && q.QuestionType != QuestionTypes.List)
                                        {
                                            if (a.SeverityLevel != SeverityLeveles.None)
                                            {
                                                if (q.QuestionType == QuestionTypes.Picture)
                                                {
                                                    var ms = ir.Medias.FirstOrDefault(m => m.AnswerId.ToString() == a.Id.ToString());
                                                    if (ms == null)
                                                        continue;
                                                }
                                                IdentifiedQuestionItem iq = new IdentifiedQuestionItem();
                                                Helper.CloneProperty(iq, q);
                                                iq.IdentifiedSeverityLevel = a.SeverityLevel;
                                                ir.IdentifiedQuestions.Add(iq);
                                            }
                                        }
                                        else
                                        {
                                            if (a.SelectedItems != null && a.SelectedItems.Count() > 0)
                                            {
                                                bool hasseveritylevel = a.SelectedItems.Count(m => m.SeverityLevel != SeverityLeveles.None) > 0;
                                                if (hasseveritylevel)
                                                {
                                                    IdentifiedQuestionItem iq = new IdentifiedQuestionItem();
                                                    Helper.CloneProperty(iq, q);

                                                    iq.IdentifiedSeverityLevel = SeverityLeveles.Low;
                                                    bool isHigh = a.SelectedItems.Count(m => m.SeverityLevel == SeverityLeveles.High) > 0;
                                                    if (isHigh)
                                                        iq.IdentifiedSeverityLevel = SeverityLeveles.High;
                                                    else
                                                    {
                                                        bool isMedium = a.SelectedItems.Count(m => m.SeverityLevel == SeverityLeveles.Medium) > 0;
                                                        if (isMedium)
                                                            iq.IdentifiedSeverityLevel = SeverityLeveles.Medium;
                                                    }
                                                    ir.IdentifiedQuestions.Add(iq);
                                                }
                                            }
                                            else
                                            {
                                                if (a.SeverityLevel != SeverityLeveles.None)
                                                {
                                                    IdentifiedQuestionItem iq = new IdentifiedQuestionItem();
                                                    Helper.CloneProperty(iq, q);
                                                    iq.IdentifiedSeverityLevel = a.SeverityLevel;
                                                    ir.IdentifiedQuestions.Add(iq);
                                                }
                                            }
                                        }

                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (!teamintelligence)
                    {
                        var aclient = FleetServiceClientHelper.CreateClient<AssetQueryClient>(SystemParams.CompanyID, sesstion.SessionID);
                        ir.Asset = aclient.GetAssetBasicInfoByID(SystemParams.CompanyID, ir.AssetId);
                    }
                    ir.IdentifiedQuestions = ir.IdentifiedQuestions.OrderByDescending(m => m.IdentifiedSeverityLevel).ToList();
                    return ir;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private byte[] GetInspectionPDF(out string fileName)
        {
            fileName = "";
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string id = Request.Params["id"];
                    bool teamintelligence = Helper.IsTrue(Request.Params["team"]);
                    byte[] bytes = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        bytes = client.GetInspectionPDF(SystemParams.CompanyID, id);
                        fileName = client.GetInspection(SystemParams.CompanyID, id).Template.Name;
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        bytes = client.GetInspectionPDF(SystemParams.CompanyID, id);
                        fileName = client.GetInspection(SystemParams.CompanyID, id).Template.Name;
                    }
                    return bytes;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        private object GetTemplates()
        {
            try
            {
                var user = GetCurrentUser();
                if (user != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    int state = 0;
                    if (!int.TryParse(ps[1], out state))
                        state = -1;
                    string filter = HttpUtility.HtmlDecode(ps[2]);

                    FormTemplateItem[] templates = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        templates = client.GetFormTemplateItems(SystemParams.CompanyID, filter, user.IID, state);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        templates = client.GetFormTemplateItems(SystemParams.CompanyID, filter, user.IID, state);
                    }
                    return templates;
                }
                else
                    return new FormTemplateItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetInspectEmailList()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    bool teamintelligence = Helper.IsTrue(clientdata);

                    UserEmailInfo[] users = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        users = client.GetInspectEmailList(SystemParams.CompanyID, string.Empty);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        users = client.GetInspectEmailList(SystemParams.CompanyID, string.Empty);
                    }
                    return users;
                }
                else
                    return new UserEmailInfo[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetTemplate()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string id = HttpUtility.HtmlDecode(ps[1]);

                    FormTemplateInfo template = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        template = client.GetFormTemplate(SystemParams.CompanyID, Convert.ToInt64(id));
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        template = client.GetFormTemplate(SystemParams.CompanyID, Convert.ToInt64(id));
                    }
                    return template;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object TemplateSaveAs()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    long srctempid = Convert.ToInt64(ps[1]);
                    string newtemplatename = HttpUtility.HtmlDecode(ps[2]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        long id = client.TemplateSaveAs(SystemParams.CompanyID, srctempid, newtemplatename, session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        long id = client.TemplateSaveAs(SystemParams.CompanyID, srctempid, newtemplatename, session.User.UID);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SaveTemplate()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    var data = HttpUtility.HtmlDecode(ps[1]);
                    FormTemplateInfo templateinfo = JsonConvert.DeserializeObject<FormTemplateInfo>(HttpUtility.HtmlDecode(data));

                    var user = UserManagement.GetUserByIID(session.User.UID);
                    if (user.UserType != UserTypes.SupperAdmin && user.UserType != UserTypes.Admin)
                        return "";

                    if (templateinfo != null)
                    {
                        if (templateinfo.Pages != null)
                        {
                            foreach (var p in templateinfo.Pages)
                            {
                                if (string.IsNullOrWhiteSpace(p.Id))
                                    p.Id = Guid.NewGuid().ToString();
                                if (p.Sections != null)
                                {
                                    foreach (var s in p.Sections)
                                    {
                                        if (string.IsNullOrWhiteSpace(s.Id))
                                            s.Id = Guid.NewGuid().ToString();

                                        if (s.Questions != null)
                                        {
                                            foreach (var q in s.Questions)
                                            {
                                                if (string.IsNullOrWhiteSpace(q.Id))
                                                    q.Id = Guid.NewGuid().ToString();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    FormTemplateInfo newtemp = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        newtemp = client.UpdateTemplate(SystemParams.CompanyID, templateinfo, session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        newtemp = client.UpdateTemplate(SystemParams.CompanyID, templateinfo, session.User.UID);
                    }
                    return new string[] { newtemp.Id.ToString(), "Saved successfully." };
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteTemplate()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    long tempid = Convert.ToInt64(ps[1]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        client.DeleteTemplate(SystemParams.CompanyID, tempid, session.User.UID, string.Empty);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.DeleteTemplate(SystemParams.CompanyID, tempid, session.User.UID, string.Empty);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object PublishTemplate()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    long tempid = Convert.ToInt64(ps[1]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        client.PublishTemplate(SystemParams.CompanyID, tempid, session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.PublishTemplate(SystemParams.CompanyID, tempid, session.User.UID);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetGlobalSections()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    var data = Request.Params["ClientData"];
                    bool teamintelligence = Helper.IsTrue(data);

                    Section[] sections = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        sections = client.GetGlobalSectionItems(SystemParams.CompanyID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        sections = client.GetGlobalSectionItems(SystemParams.CompanyID);
                    }
                    return sections;
                }
                else
                    return new Section[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetGlobalQuestions()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string sectionid = HttpUtility.HtmlDecode(ps[1]);

                    Question[] questions = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        questions = client.GetGlobalQuestions(SystemParams.CompanyID, sectionid);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        questions = client.GetGlobalQuestions(SystemParams.CompanyID, sectionid);
                    }
                    return questions;
                }
                else
                    return new Question[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object SaveGlobalSection()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    var data = HttpUtility.HtmlDecode(ps[1]);
                    Section sec = JsonConvert.DeserializeObject<Section>(data);

                    if (string.IsNullOrEmpty(sec.Id))
                        sec.Id = Guid.NewGuid().ToString();

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        client.UpdateGlobalSectionItem(SystemParams.CompanyID, sec, session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.UpdateGlobalSectionItem(SystemParams.CompanyID, sec, session.User.UID);
                    }

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

        private object SaveGlobalQuestion()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] data = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(data[0]);
                    string sectioinid = data[1];
                    Question q = JsonConvert.DeserializeObject<Question>(HttpUtility.HtmlDecode(data[2]));

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        if (string.IsNullOrEmpty(q.Id))
                        {
                            q.Id = Guid.NewGuid().ToString();
                            client.AddGlobalQuestion(SystemParams.CompanyID, sectioinid, q, session.User.UID);
                        }
                        else
                        {
                            client.UpdateGlobalQuestion(SystemParams.CompanyID, sectioinid, q, session.User.UID);
                        }
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        if (string.IsNullOrEmpty(q.Id))
                        {
                            q.Id = Guid.NewGuid().ToString();
                            client.AddGlobalQuestion(SystemParams.CompanyID, sectioinid, q, session.User.UID);
                        }
                        else
                        {
                            client.UpdateGlobalQuestion(SystemParams.CompanyID, sectioinid, q, session.User.UID);
                        }
                    }

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

        private object DeleteGlobalSection()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string sectionid = HttpUtility.HtmlDecode(ps[1]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        client.DeleteGlobalSection(SystemParams.CompanyID, sectionid, "", session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.DeleteGlobalSection(SystemParams.CompanyID, sectionid, "", session.User.UID);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object DeleteGlobalQuestion()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string questionid = HttpUtility.HtmlDecode(ps[1]);

                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        client.DeleteGlobalQuestion(SystemParams.CompanyID, questionid, "", session.User.UID);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        client.DeleteGlobalQuestion(SystemParams.CompanyID, questionid, "", session.User.UID);
                    }
                    return "OK";
                }
                else
                {
                    return "Failed";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetGlobalSectionsByID()
        {
            try
            {
                if (GetCurrentLoginSession() != null)
                {
                    string clientdata = Request.Params["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    bool teamintelligence = Helper.IsTrue(ps[0]);
                    string[] sids = JsonConvert.DeserializeObject<string[]>(ps[1]);

                    Section[] sections = null;
                    if (teamintelligence)
                    {
                        var client = CreateClient<TeamIntelligenceClient>();
                        sections = client.GetGlobalSection(SystemParams.CompanyID, sids);
                    }
                    else
                    {
                        var client = CreateClient<AssetInspectClient>();
                        sections = client.GetGlobalSection(SystemParams.CompanyID, sids);
                    }
                    return sections;
                }
                else
                    return new Section[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private object GetAssetMakes()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    AssetMake[] makes = CreateClient<AssetClassProvider>().GetAssetMakes(string.Empty);
                    List<AssetMakeItem> ls = new List<AssetMakeItem>();
                    foreach (var mk in makes)
                    {
                        AssetMakeItem item = new AssetMakeItem();
                        Helper.CloneProperty(item, mk);
                        ls.Add(item);
                    }
                    return ls.OrderBy(m => m.Name).ToArray();

                }
                else
                    return new AssetMakeItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetAssetModels()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    var clientdata = Request.Form["ClientData"];
                    string[] ps = JsonConvert.DeserializeObject<string[]>(clientdata);
                    int makeid = -1;
                    int.TryParse(ps[0], out makeid);
                    var searchtxt = HttpUtility.HtmlDecode(ps[1]);

                    AssetModel[] models = CreateClient<AssetClassProvider>().GetAssetModels(makeid, searchtxt);
                    List<AssetModelItem> ls = new List<AssetModelItem>();
                    foreach (var md in models)
                    {
                        AssetModelItem item = new AssetModelItem();
                        Helper.CloneProperty(item, md);
                        if (md.MakeId > 0)
                        {
                            item.MakeID = md.MakeId;
                            item.MakeName = md.MakeName;
                        }
                        if (md.TypeId > 0)
                        {
                            item.TypeID = md.TypeId;
                            item.TypeName = md.TypeName;
                        }
                        ls.Add(item);
                    }

                    return ls.OrderBy(m => m.Name).ToArray();
                }
                else
                    return new AssetModelItem[0];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private object GetAssetTypes()
        {
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    AssetType[] types = CreateClient<AssetClassProvider>().GetAssetTypes(SystemParams.CompanyID);
                    types = types.OrderBy((t) => t.Name).ToArray();
                    List<StringKeyValue> list = new List<StringKeyValue>();
                    foreach (AssetType md in types)
                    {
                        StringKeyValue kv = new StringKeyValue();
                        kv.Key = md.ID.ToString();
                        kv.Value = md.Name;
                        list.Add(kv);
                    }
                    return list.ToArray();

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

    class AssetInspectInfo : AssetInspectItem
    {
        public string CommitTimeStr { get { return CommitTime == DateTime.MinValue ? "" : CommitTime.ToString(("M/d/yyyy h:mm tt")); } }
        public string CommitTimeLocalStr { get { return CommitTimeLocal == DateTime.MinValue ? "" : CommitTimeLocal.ToString(("M/d/yyyy h:mm tt")); } }
    }
    class TeamInspectInfo : TeamInspectItem
    {
        public string CommitTimeStr { get { return CommitTime == DateTime.MinValue ? "" : CommitTime.ToString(("M/d/yyyy h:mm tt")); } }
        public string CommitTimeLocalStr { get { return CommitTimeLocal == DateTime.MinValue ? "" : CommitTimeLocal.ToString(("M/d/yyyy h:mm tt")); } }
    }

    class InspectReportItem : InspectReportInfo
    {
        public AssetBasicInfo Asset { get; set; }
        public string CommitTimeStr { get { return CommitTime == DateTime.MinValue ? "" : CommitTime.ToString(("M/d/yyyy h:mm tt")); } }
        public string CommitTimeLocalStr { get { return CommitTimeLocal == default ? "" : CommitTimeLocal.ToString(("M/d/yyyy h:mm tt")); } }
        public List<IdentifiedQuestionItem> IdentifiedQuestions { get; set; }
    }
    class IdentifiedQuestionItem : Question
    {
        public SeverityLeveles IdentifiedSeverityLevel { get; set; }
    }
    class InspectReportEditItem : InspectReportInfo
    {
        public AssetBasicInfo Asset { get; set; }
        public string CommitTimeStr { get { return CommitTime == DateTime.MinValue ? "" : CommitTime.ToString(("M/d/yyyy h:mm tt")); } }
        public string CommitTimeLocalStr { get { return CommitTimeLocal == default ? "" : CommitTimeLocal.ToString(("M/d/yyyy h:mm tt")); } }
        public UserEmailInfo[] EmailList { get; set; }
        public AssetBasicInfo[] AssetList { get; set; }
        public JobSiteLimitItem[] JobSiteList { get; set; }
    }
}

