using Foresight.Fleet.Services.Asset;
using Foresight.Fleet.Services.OTRConfig;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IronIntel.Contractor.OTRConfig
{
    public class HarshDrivingManagement
    {
        public static HarshDrivingItem[] GetHarshDrivingEvents(string sessionid, DateTime startdate, DateTime enddate, string searchtxt, string useriid)
        {
            HarshDrivingInfo[] hds = FleetServiceClientHelper.CreateClient<OTRConfigClient>(sessionid).GetHarshDrivingEvents(SystemParams.CompanyID, startdate, enddate);
            if (hds == null || hds.Length == 0)
                return new HarshDrivingItem[0];

            long[] availableAssetsids = null;
            var user = Users.UserManagement.GetUserByIID(useriid);
            if (user.UserType < Users.UserTypes.Admin)
                availableAssetsids = FleetServiceClientHelper.CreateClient<AssetQueryClient>(sessionid).GetAvailableAssetsForUsers(SystemParams.CompanyID, useriid);

            List<HarshDrivingItem> list = new List<HarshDrivingItem>();
            foreach (HarshDrivingInfo hd in hds)
            {
                if (user.UserType < Users.UserTypes.Admin && !availableAssetsids.Contains(hd.AssetID))
                    continue;
                HarshDrivingItem item = new HarshDrivingItem();
                Helper.CloneProperty(item, hd);

                if (!string.IsNullOrEmpty(searchtxt))
                {
                    if (Helper.Contains(item.VIN, searchtxt)
                    || Helper.Contains(item.AssetID.ToString(), searchtxt)
                    || Helper.Contains(item.Name, searchtxt)
                    || Helper.Contains(item.Name2, searchtxt)
                    || Helper.Contains(item.MakeName, searchtxt)
                    || Helper.Contains(item.TypeName, searchtxt)
                    || Helper.Contains(item.ModelName, searchtxt)
                    || Helper.Contains(item.Street, searchtxt)
                    || Helper.Contains(item.City, searchtxt)
                    || Helper.Contains(item.State, searchtxt)
                    || Helper.Contains(item.PostalCode, searchtxt))
                    {
                        list.Add(item);
                    }
                }
                else
                    list.Add(item);
            }

            return list.ToArray();
        }

        public static void ExcludedHarshDrivingEvents(string sessionid, HarshDrivintClient hd, string useriid)
        {
            long[] logids = new long[] { hd.LogID };
            var client = FleetServiceClientHelper.CreateClient<OTRConfigClient>(sessionid);
            if (hd.Excluded)
                client.IncludedHarshDrivingEvents(SystemParams.CompanyID, hd.AssetID, logids, useriid, hd.Notes);
            else
                client.ExcludedHarshDrivingEvents(SystemParams.CompanyID, hd.AssetID, logids, useriid, hd.Notes);
        }

    }
}
