using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimpleCore;
using SimpleCore.PropType;

namespace StandardScene.CarTypes
{
    internal class VDA5050Helper
    {
        /// <summary>
        /// If true, use Simple "id" field as VDA5050 id.
        /// If false, use Simple "name" field as VDA5050 id.
        /// </summary>
        public static bool UseSimpleId = true;

        public static T FindByVDA5050Id<T>(string vda5050Id) where T : Prop
        {
            Func<Prop, bool> testFunc = UseSimpleId ? prop => $"{prop.id}" == vda5050Id : prop => prop.name == vda5050Id;

            var matches = SimpleLib.Things().OfType<T>().Where(prop => testFunc(prop)).ToList();
            if (matches.Count == 0) return null;
            if (matches.Count > 1)
                throw new Exception(
                    $"multiple Props have same name {vda5050Id}, matches: {string.Join(", ", matches.Select(pp => $"{pp.id}({pp.GetType()})"))}");
            return matches[0];
        }

        public static string GetVDA5050Id(int propId)
        {
            return UseSimpleId ? $"{propId}" : SimpleLib.Things().Where(pp => pp.id == propId).FirstOrDefault().name;
        }

        public static string GetVDA5050Id(Prop prop)
        {
            return UseSimpleId ? $"{prop.id}" : prop.name;
        }

        public static Site FindSiteByVDA5050Id(string vda5050Id)
        {
            return FindByVDA5050Id<Site>(vda5050Id);
        }

        public static Track FindTrackByVDA5050Id(string vda5050Id)
        {
            return FindByVDA5050Id<Track>(vda5050Id);
        }

        public static AbstractCar FindCarByVDA5050Id(string vda5050Id)
        {
            return FindByVDA5050Id<AbstractCar>(vda5050Id);
        }
    }
}
