using Foresight;
using Foresight.Data;
using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.JobSite;
using Foresight.ServiceModel;
using IronIntel.Contractor.Machines;
using IronIntel.Contractor.MapView;
using IronIntel.Contractor.Shape;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace IronIntel.Contractor.JobSites
{
    public class JobSitesManagement
    {
        private const string MachineFields = "{0}MACHINEID,{0}MACHINENAME,{0}MAKEID,{0}MODELID,{0}TYPEID,{0}MACHINEICONID,{0}DEVICEID,{0}VIN,{0}MAKEYEAR,{0}NOTES,{0}STATUS,{0}CONTRACTORID,{0}DEALERID,{0}UID,{0}ADDEDON,{0}CUR_LONGITUDE,{0}CUR_LATITUDE,{0}LOCDATE_UTC,{0}ENGINEHOURS,{0}HOURSDATE_UTC,{0}DATASOURCE,{0}HIDE,{0}FUEL_CONSUMED,{0}FUEL_UNITS,{0}FUEL_DATE,{0}ODOMETER,{0}ODODATE_UTC,{0}ODOMETERUOM,{0}FUELCOST,{0}FUELCOSTUOM,{0}MACHINERATE,{0}WORKTYPE,{0}RETIREMENTHOURS,{0}RETIREMENTODO,{0}ALTITUDE,{0}ALTITUDEUNITS,{0}IDLEHOURSUTC,{0}IDLEHOURS,{0}LOADCOUNTUTC,{0}LOADCOUNT,{0}PAYLOADTOTALUTC,{0}PAYLOADTOTAL,{0}PAYLOADTOTALUNITS,{0}DEFREMAININGUTC,{0}DEFREMAINING,{0}FUELREMAININGUTC,{0}FUELREMAININGPERCENT,{0}MACHINENAME2,{0}ONROAD,{0}LEASESTART,{0}LEASEEND,{0}LEASEHOURS,{0}UNDERCARRIAGEHOURS,{0}ODOSTART2,{0}ISDELETED,{0}DELETEDDATE,{0}ODOSTART2DATASOURCE,{0}LOCDATASOURCE,{0}HOURSDATASOURCE,{0}FUELDATASOURCE,{0}AQUISITIONTYPE,{0}ICONFILENAME,{0}STARTINGENGINEHOURS,{0}DISTANCECALCBY,{0}TELEMATICSENABLED,{0}COSTCENTER,{0}EQCLASS,{0}DESCRIPTION";

        
        public static void RefreshJobsiteAssets(string sessionid, long jobsiteid)
        {
            System.Threading.ThreadPool.QueueUserWorkItem((object state) =>
            {
                try
                {
                    FleetServiceClientHelper.CreateClient<JobSiteProvider>(sessionid).RefreshAllJobSites(SystemParams.CompanyID, jobsiteid);
                }
                catch { }
            }, null);
        }

        public static void AddMachinesToJobSite(JobSiteViewItem jobsite)
        {
            if (jobsite != null)
            {
                const string SQL_t = @"if exists(select 1 from JOBSITEMACHINES where JOBSITEID={0} and MACHINEID={1}) update JOBSITEMACHINES set ONSITE={3} where JOBSITEID={0} and MACHINEID = {1} else insert into JOBSITEMACHINES(JOBSITEID,MACHINEID,VIN,ADDEDON,ONSITE) values({0},{1},{2},getutcdate(),{3})";
                const string SQL_upt = "update JOBSITEMACHINES set ONSITE=0 where JOBSITEID!={0} and MACHINEID={1}";
                const string SQL_del = "select MACHINEID from JOBSITEMACHINES where JOBSITEID={0} ";
                const string SQL_OUT = "exec pro_removejobsitemachines {0},{1},{2},{3},{4},{5},{6},{7}";

                string ad = string.Empty;
                if (jobsite.Machines != null && jobsite.Machines.Length > 0)
                {
                    string machineids = string.Join(",", jobsite.Machines.Select(m => m.AssetId));
                    ad = "  and MACHINEID not in(" + machineids + ")";
                }

                using (FISqlTransaction tran = new FISqlTransaction(SystemParams.DataDbConnectionString))
                {
                    DataTable dt = tran.GetDataTableBySQL(SQL_del + ad, jobsite.ID);
                    foreach (DataRow dr in dt.Rows)
                    {
                        string mid = FIDbAccess.GetFieldString(dr["MACHINEID"], "");
                        tran.ExecSQL(SQL_OUT, mid, jobsite.ID, DateTime.Now.ToUniversalTime(), null, null, null, null, "ManualRemove");
                    }

                    if (jobsite.Machines != null && jobsite.Machines.Length > 0)
                    {
                        foreach (var mac in jobsite.Machines)
                        {
                            if (mac.OnSite)
                            {
                                tran.ExecSQL(SQL_upt, jobsite.ID, mac.AssetId);
                            }

                            tran.ExecSQL(SQL_t, jobsite.ID, mac.AssetId, mac.VIN, mac.OnSite ? 1 : 0);
                        }
                    }
                    tran.Commit();
                }
            }

        }

        private static JobSiteViewItem ConvertToJobSiteViewItem(DataRow dr)
        {
            JobSiteViewItem js = new JobSiteViewItem();
            long JobSiteId = FIDbAccess.GetFieldInt(dr["JOBSITEID"], 0);
            js.ID = FIDbAccess.GetFieldInt(dr["JOBSITEID"], 0);
            js.Name = FIDbAccess.GetFieldString(dr["JOBSITENAME"], string.Empty);
            js.Latitude = FIDbAccess.GetFieldDouble(dr["LATITUDE"], 0);
            js.Longitude = FIDbAccess.GetFieldDouble(dr["LONGITUDE"], 0);
            js.Radius = FIDbAccess.GetFieldDouble(dr["RADIUS"], 0);
            js.Radius_UOM = FIDbAccess.GetFieldString(dr["RADUIS_UOM"], string.Empty);
            if (string.IsNullOrWhiteSpace(js.Radius_UOM))
                js.Radius_UOM = "Mile";
            js.ContractorID = FIDbAccess.GetFieldString(dr["CONTRACTORID"], string.Empty);
            js.ColorString = FIDbAccess.GetFieldString(dr["COLOR"], string.Empty);
            System.Drawing.Color color = System.Drawing.Color.Orange;
            try
            {
                color = System.Drawing.ColorTranslator.FromHtml(js.ColorString);
            }
            catch
            {
            }
            js.Color = new IIColor() { Alpha = color.A, Red = color.R, Green = color.G, Blue = color.B };

            js.Notes = FIDbAccess.GetFieldString(dr["NOTES"], string.Empty);
            js.StartDate = FIDbAccess.GetFieldDateTime(dr["STARTDATE"], DateTime.MinValue);
            js.EndDate = FIDbAccess.GetFieldDateTime(dr["ENDDATE"], DateTime.MinValue);
            string polygon = FIDbAccess.GetFieldString(dr["POLYGON"], string.Empty);
            js.Polygon = ConvertPolygonToPointItem(polygon);
            js.BaseOnMachineID = FIDbAccess.GetFieldInt(dr["BASEONMACHINEID"], 0);
            js.IsDeleted = FIDbAccess.GetFieldInt(dr["ISDELETED"], 0) == 1;
            if (js.IsDeleted)
                js.Name = js.Name + " - Deleted";
            return js;
        }

        private static PostionItem[] ConvertPolygonToPointItem(string polygon)
        {
            if (string.IsNullOrWhiteSpace(polygon))
                return null;

            List<PostionItem> list = new List<PostionItem>();
            var polygons = polygon.Split(';');
            foreach (var py in polygons)
            {
                PostionItem pi = new PostionItem();
                var sap = py.Split(',');
                pi.Latitude = Convert.ToDouble(sap[0]);
                pi.Longitude = Convert.ToDouble(sap[1]);
                list.Add(pi);
            }
            return list.ToArray();
        }

        public static MachineTypeItem[] GetMachineTypes()
        {
            List<MachineTypeItem> mTypes = new List<MachineTypeItem>();
            AssetType[] types = MachineManagement.GetMachineTypes();
            if (types != null)
            {
                foreach (var t in types)
                {
                    mTypes.Add(new MachineTypeItem() { ID = t.ID, Name = t.Name });
                }
            }
            return mTypes.ToArray();
        }

        /// <summary>
        /// 从Shape文件导入Jobsite范围
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static MapPoint[] ImportJobsitePolygon(string filename, byte[] buffer)
        {
            Shape.Shape shape = new Shape.Shape();
            if (filename.EndsWith(".shp", StringComparison.OrdinalIgnoreCase))
                ShapeFileParser.ParseFromShapeFile(buffer, shape);
            else if (filename.EndsWith(".kml", StringComparison.OrdinalIgnoreCase))
                ShapeFileParser.ParseFromKMLFile(buffer, shape);
            else if (filename.EndsWith(".kmz", StringComparison.OrdinalIgnoreCase))
                ShapeFileParser.ParseFromKMZFile(buffer, shape);
            if (shape.Polygons.Count > 0 && shape.Polygons[0].Rings.Count > 0)
            {
                return shape.Polygons[0].Rings[0].Points.ToArray();
            }
            return new MapPoint[0];
        }
    }
}
