using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCS.Core;

namespace WCS.Core
{ 
    public class DevicePath
    {
        public string From { get; set; } = "";
        public string To { get; set; } = "";

        List<string> points = new List<string>();

        public List<Device> Points
        {
            get 
            {
                var list = points.Select(v => Device.Find(v)).ToList();
                return list;
            }
        }

        public static DevicePath[] GetPaths(string from, string to)
        {
            var all = Device.All.ToDictionary(v => v.Code, v => v.Targets.Select(d => d.Code).ToList());

            List<List<string>> pathList = new List<List<string>>();
            recursion(from, to, all, pathList, new List<string>());
            pathList.ForEach(path => path.Remove(from));

            var arr = pathList.Select(v => new DevicePath { From = from, To = to, points = v }).ToArray();
            return arr;
        }

        public static DevicePath? GetPath(string from, string to)
        {
            return GetPaths(from, to).OrderBy(v => v.Points.Count).FirstOrDefault();
        }

        static void recursion(string from, string to, Dictionary<string, List<string>> all,List<List<string>> pathList, List<string> points)
        {
            if (points.Count > 100)
                return;
            points.Add(from);
            if (from == to)
            {
                pathList.Add(points);
                return;
            }
            if (!all.ContainsKey(from))
            {
                return;
            }
            foreach (var code in all[from])
            {
                if (points.Contains(code))
                    continue;
                recursion(code, to, all, pathList, new List<string>(points));
            }
        }
    }


}
