using Foresight.Fleet.Services.FITracker;
using Foresight.Fleet.Services.JobSite;
using IronIntel.Contractor.FITracker;
using IronIntel.Contractor.JobSites;
using IronIntel.Contractor.MapView;
using IronIntel.Services;
using IronIntel.Services.Business.Admin;
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 FITrackerBasePage : ContractorBasePage
    {
        protected void ProcessRequest()
        {
            object result = null;
            try
            {
                string methodName = Request.Params["MethodName"];
                if (methodName != null)
                {
                    switch (methodName)
                    {
                        case "GetTrackers":
                            result = GetTrackers();
                            break;
                        case "GetMessages":
                            result = GetMessages();
                            break;
                        case "PostMessage":
                            result = PostMessage();
                            break;
                        case "GetJobsites":
                            result = GetJobsites();
                            break;
                        case "ChangeAcceptableAccuracy":
                            result = ChangeAcceptableAccuracy();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("error", "FITrackerBasePage", ex.Message, ex.ToString());
                throw ex;
            }
            string json = JsonConvert.SerializeObject(result);
            Response.Write(json);
            Response.End();
        }

        private object GetTrackers()
        {
            var session = GetCurrentLoginSession();
            TrackerDeviceItem[] items = null;
            if (session != null)
            {
                var s = Request.Form["ClientData"];
                s = HttpUtility.HtmlDecode(s);

                List<TrackerDeviceItem> result = new List<TrackerDeviceItem>();
                var ds = FITrackerManagement.GetTrackerDevices(session.SessionID, "");
                foreach (MobileDeviceInfo di in ds)
                {
                    TrackerDeviceItem d = new TrackerDeviceItem();
                    Helper.CloneProperty(d, di);
                    result.Add(d);
                }
                items = result.OrderBy(d => d.DeviceName).ToArray();
            }
            else
            {
                items = new TrackerDeviceItem[0];
            }
            return items;
        }

        private object GetMessages()
        {
            TrackerChatMessage[] items = null;
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                string s = Request.Form["ClientData"];
                var obj = JsonConvert.DeserializeObject<string[]>(s);
                string deviceid = obj[0];
                long lastmsgid = -1;
                if (!long.TryParse(obj[1], out lastmsgid))
                    lastmsgid = -1;

                List<TrackerChatMessage> result = new List<TrackerChatMessage>();
                var msgs = FITrackerManagement.GetMessages(session.SessionID, deviceid, lastmsgid);
                double hourOffset = SystemParams.GetHoursOffset();
                foreach (ChatMessageInfo msginfo in msgs)
                {
                    TrackerChatMessage msg = new TrackerChatMessage();
                    Helper.CloneProperty(msg, msginfo);
                    if (msg.Time != DateTime.MinValue)
                        msg.Time = msg.Time.AddHours(hourOffset);
                    msg.IsSelf = session.User.UID.Equals(msg.SenderID, StringComparison.OrdinalIgnoreCase);
                    result.Add(msg);
                }
                items = result.ToArray();
            }
            return items;
        }

        private object PostMessage()
        {
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                var s = Request.Form["ClientData"];
                s = HttpUtility.HtmlDecode(s);
                var obj = JsonConvert.DeserializeObject<string[]>(s);
                int type = 0;
                int.TryParse(obj[2], out type);
                var msginfo = FITrackerManagement.PostMessage(session.SessionID, obj[0], session.User.UID, session.User.Name, obj[1], type);
                double hourOffset = SystemParams.GetHoursOffset();

                TrackerChatMessage msg = new TrackerChatMessage();
                Helper.CloneProperty(msg, msginfo);
                if (msg.Time != DateTime.MinValue)
                    msg.Time = msg.Time.AddHours(hourOffset);
                msg.IsSelf = session.User.UID.Equals(msg.SenderID, StringComparison.OrdinalIgnoreCase);
                return msg;
            }
            return "Failed";
        }

        private object ChangeAcceptableAccuracy()
        {
            var session = GetCurrentLoginSession();
            if (session != null)
            {
                var s = Request.Form["ClientData"];
                s = HttpUtility.HtmlDecode(s);
                var obj = JsonConvert.DeserializeObject<string[]>(s);
                double accuracy = 0;
                double.TryParse(obj[1], out accuracy);
                FITrackerManagement.ChangeAcceptableAccuracy(session.SessionID, obj[0], accuracy, obj[2], session.User.UID);
                return "";
            }
            return "Failed";
        }

        private object GetJobsites()
        {
            try
            {
                JobSiteViewItem[] items = null;
                if (GetCurrentLoginSession() != null)
                {
                    var jss = CreateClient<JobSiteProvider>().GetJobSiteItems(SystemParams.CompanyID, "", false);
                    List<JobSiteViewItem> list = new List<JobSiteViewItem>();
                    foreach (var js in jss)
                    {
                        JobSiteViewItem item = new JobSiteViewItem();
                        item.ID = js.ID;
                        item.Name = js.Name;
                        item.BaseOnMachineID = js.BaseonMachineID;
                        item.Code = js.Code;
                        item.Types = new string[] { js.JobSiteTypes };
                        item.ColorString = js.Color;
                        System.Drawing.Color color = System.Drawing.Color.Orange;
                        try
                        {
                            color = System.Drawing.ColorTranslator.FromHtml(item.ColorString);
                        }
                        catch
                        {
                        }
                        item.Color = new IIColor() { Alpha = color.A, Red = color.R, Green = color.G, Blue = color.B };

                        item.Latitude = js.Latitude;
                        item.Longitude = js.Longitude;
                        item.StartDate = js.StartDate == null ? DateTime.MinValue : js.StartDate.Value;
                        item.EndDate = js.EndDate == null ? DateTime.MinValue : js.EndDate.Value;
                        item.Radius = js.Radius;
                        item.Radius_UOM = js.RadiusUOM;
                        if (js.Polygon != null && js.Polygon.Length > 0)
                        {
                            List<PostionItem> temps = new List<PostionItem>();
                            foreach (var p in js.Polygon)
                            {
                                temps.Add(new PostionItem(p.Latitude, p.Longtitude));
                            }
                            item.Polygon = temps.ToArray();
                        }

                        list.Add(item);
                    }
                    items = list.ToArray();
                }
                else
                {
                    items = new JobSiteViewItem[0];
                }
                return items;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public class TrackerDeviceItem
        {
            public string DeviceID { get; set; }
            public string DeviceName { get; set; }
            public string DeviceType { get; set; }
            public long AssetID { get; set; }
            public string VIN { get; set; }
            public string Name { get; set; }
            public string Make { get; set; }
            public string Model { get; set; }
            public string Type { get; set; }
            public string ContractorID { get; set; }
            public string DealerID { get; set; }
            public long ShiftHistoryID { get; set; }
            public bool ThirdPartyMode { get; set; }
            public double AcceptableAccuracy { get; set; }
        }

        public class TrackerChatMessage
        {
            public long AssetID { get; set; }
            public string ReceiverName { get; set; }
            public string ReceiverID { get; set; }
            public string SenderType { get; set; }
            public string SenderName { get; set; }
            public string SenderID { get; set; }
            public string ContractorID { get; set; }
            public string TextMessage { get; set; }
            public int MessageType { get; set; }
            public DateTime Time { get; set; }
            public long ID { get; set; }
            public string ReceiverType { get; set; }
            public bool IsSelf { get; set; }
            public string TimeText
            {
                get
                {
                    if (Time != DateTime.MinValue)
                    {
                        return Time.ToString();
                    }
                    return "";
                }
            }
        }
    }
}
