using FI.FIC.Extention;
using Foresight.Fleet.Services.Asset;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IronIntel.Contractor.FICExtDataTable
{
    public class AssetTripsDataTable : FleetExtDataTable
    {
        public override string ID
        {
            get
            {
                return "32F84217-7F99-438E-9F06-6F238DDA3202";
            }
        }

        public override string Name
        {
            get
            {
                return "Asset Trips DataTable";
            }
        }

        public override string Description
        {
            get
            {
                return "Asset Trips DataTable";
            }
        }

        public override string Version
        {
            get
            {
                return "1.0.0.0";
            }
        }

        private static ExtDataTableParameter[] Params = new ExtDataTableParameter[] {
            new ExtDataTableParameter(){ID="C854AF5C-2928-43E1-B600-30F0318006FA",
                Name ="AssetId",DataType=DataTypes.Integer,DefaultValue=0 },
            new ExtDataTableParameter(){ ID="8573483C-3FD3-42E0-8C80-5DE543183140",
                Name ="StartDate",DataType=DataTypes.DateTime,DefaultValue=DateTime.Today.ToShortDateString()},
            new ExtDataTableParameter(){ ID="2C82E11F-2D97-426B-9925-FFB9BA3AF8D0",
                Name ="EndDate",DataType=DataTypes.DateTime,DefaultValue=DateTime.Today.ToShortDateString()},
        };

        public override ExtDataTableParameter[] AvailableParameters
        {
            get
            {
                return Params;
            }
        }

        public override DataTable GetData(int maxrows, KeyValuePair<string, object>[] parameters)
        {
            DataTable result = GetSchemaTable();
            string companyid = SystemParams.CompanyID;
            string assetidStr = "";
            string dtFromStr = "";
            string dtToStr = "";

            if (parameters != null)
            {
                foreach (var kv in parameters)
                {
                    if (kv.Key.Equals("AssetId", StringComparison.OrdinalIgnoreCase))
                        assetidStr = kv.Value == null ? "" : kv.Value.ToString();
                    else if (kv.Key.Equals("StartDate", StringComparison.OrdinalIgnoreCase))
                        dtFromStr = kv.Value == null ? "" : kv.Value.ToString();
                    else if (kv.Key.Equals("EndDate", StringComparison.OrdinalIgnoreCase))
                        dtToStr = kv.Value == null ? "" : kv.Value.ToString();
                }
            }
            var user = GetCurrentUser();
            if (user == null || !user.Active)
            {
                return result;
            }

            long assetid = 0;
            if (string.IsNullOrEmpty(assetidStr) || !long.TryParse(assetidStr, out assetid))
                return result;
            if (assetid <= 0)
            {
                return result;
            }
            DateTime dtFrom = DateTime.Today;
            DateTime dtTo = DateTime.Now;
            if (!DateTime.TryParse(dtFromStr, out dtFrom) || !DateTime.TryParse(dtToStr, out dtTo))
                return result;
            dtTo = dtTo.Date.AddDays(1).AddSeconds(-1);

            try
            {
                var aclient = FleetServiceClientHelper.CreateClient<AssetQueryClient>(companyid, string.Empty);
                var asset = aclient.GetAssetBasicInfoByID(companyid, assetid);
                if (asset == null)
                    return result;

                var client = FleetServiceClientHelper.CreateClient<AssetLocationQueryClient>(companyid, string.Empty);
                AssetTripInfo[] trips = client.GetAssetTripLins(companyid, assetid, dtFrom.Date, dtTo);
                foreach (AssetTripInfo trip in trips)
                {
                    DataRow dr = result.NewRow();
                    result.Rows.Add(dr);
                    FillRowData(dr, trip, asset);
                }
            }
            catch (Exception ex)
            {
                WriteLog(GetType().FullName + ".GetData", ex.Message, ex.ToString());
            }

            return result;
        }

        public override DataTable GetSchemaTable()
        {
            DataTable result = new DataTable();
            result.Columns.Add("MachineID", typeof(long));
            result.Columns.Add("Name", typeof(string));
            result.Columns.Add("Name2", typeof(string));
            result.Columns.Add("VIN", typeof(string));
            result.Columns.Add("MakeID", typeof(int));
            result.Columns.Add("Make", typeof(string));
            result.Columns.Add("ModelID", typeof(int));
            result.Columns.Add("Model", typeof(string));
            result.Columns.Add("TypeID", typeof(int));
            result.Columns.Add("Type", typeof(string));

            result.Columns.Add("TripOnLogId", typeof(long));
            result.Columns.Add("TripOnAsofTime", typeof(DateTime));
            result.Columns.Add("TripOnLocalAsofTime", typeof(DateTime));
            result.Columns.Add("TripOnLatitude", typeof(double));
            result.Columns.Add("TripOnLongitude", typeof(double));
            result.Columns.Add("TripOnOdometer", typeof(double));
            result.Columns.Add("TripOnOdometerUnit", typeof(string));
            result.Columns.Add("TripOnCity", typeof(string));
            result.Columns.Add("TripOnStreet", typeof(string));
            result.Columns.Add("TripOnState", typeof(string));

            result.Columns.Add("TripOffLogId", typeof(long));
            result.Columns.Add("TripOffAsofTime", typeof(DateTime));
            result.Columns.Add("TripOffLocalAsofTime", typeof(DateTime));
            result.Columns.Add("TripOffLatitude", typeof(double));
            result.Columns.Add("TripOffLongitude", typeof(double));
            result.Columns.Add("TripOffOdometer", typeof(double));
            result.Columns.Add("TripOffOdometerUnit", typeof(string));
            result.Columns.Add("TripOffCity", typeof(string));
            result.Columns.Add("TripOffStreet", typeof(string));
            result.Columns.Add("TripOffState", typeof(string));

            result.Columns.Add("TripOff", typeof(DateTime));
            result.Columns.Add("TripTime", typeof(TimeSpan));
            result.Columns.Add("TripDistance", typeof(double));
            result.Columns.Add("TripDistanceUnit", typeof(string));

            result.TableName = "AssetTrips";

            return result;
        }

        private void FillRowData(DataRow dr, AssetTripInfo trip, AssetBasicInfo asset)
        {
            dr["MachineID"] = asset.ID;
            dr["Name"] = asset.Name;
            dr["Name2"] = asset.Name2;
            dr["VIN"] = asset.VIN;
            dr["MakeID"] = asset.MakeID;
            dr["Make"] = asset.MakeName;
            dr["ModelID"] = asset.ModelID;
            dr["Model"] = asset.ModelName;
            dr["TypeID"] = asset.TypeID;
            dr["Type"] = asset.TypeName;
            if (trip.TripOn != null)
            {
                dr["TripOnLogId"] = trip.TripOn.LogId;
                dr["TripOnAsofTime"] = trip.TripOn.AsofTime;
                dr["TripOnLocalAsofTime"] = trip.TripOn.LocalAsofTime;
                dr["TripOnLatitude"] = trip.TripOn.Latitude;
                dr["TripOnLongitude"] = trip.TripOn.Longitude;
                if (trip.TripOn.Odometer != null)
                {
                    dr["TripOnOdometer"] = trip.TripOn.Odometer;
                    dr["TripOnOdometerUnit"] = trip.TripOn.OdometerUnit;
                }
                dr["TripOnCity"] = trip.TripOn.City;
                dr["TripOnStreet"] = trip.TripOn.Street;
                dr["TripOnState"] = trip.TripOn.State;
            }
            if (trip.TripOff != null)
            {
                dr["TripOffLogId"] = trip.TripOff.LogId;
                dr["TripOffAsofTime"] = trip.TripOff.AsofTime;
                dr["TripOffLocalAsofTime"] = trip.TripOff.LocalAsofTime;
                dr["TripOffLatitude"] = trip.TripOff.Latitude;
                dr["TripOffLongitude"] = trip.TripOff.Longitude;
                if (trip.TripOff.Odometer != null)
                {
                    dr["TripOffOdometer"] = trip.TripOff.Odometer;
                    dr["TripOffOdometerUnit"] = trip.TripOff.OdometerUnit;
                }
                dr["TripOffCity"] = trip.TripOff.City;
                dr["TripOffStreet"] = trip.TripOff.Street;
                dr["TripOffState"] = trip.TripOff.State;
            }
            if (trip.TripTime != null)
                dr["TripTime"] = trip.TripTime;
            if (trip.TripDistance != null)
                dr["TripDistance"] = trip.TripDistance;
            dr["TripDistanceUnit"] = trip.TripDistanceUnit;
        }
    }
}
