using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SemiPoint = SemiconductorVisionAlgorithm.SemiParams.Point;

namespace MainShell.AlgorithmCalib.Service
{
    public static class CalibFileService
    {
        public static void SaveCalibPointsFile(string path, List<SemiPoint> real, List<SemiPoint> ruler)
        {
            using (var sw = new StreamWriter(path))
            {
                sw.WriteLine("# realX, realY, rulerX, rulerY");
                int count = Math.Max(real.Count, ruler.Count);
                for (int i = 0; i < count; i++)
                {
                    var r = i < real.Count ? real[i] : new SemiPoint(0, 0);
                    var u = i < ruler.Count ? ruler[i] : new SemiPoint(0, 0);
                    sw.WriteLine($"{r.X},{r.Y},{u.X},{u.Y}");
                }
            }
        }

        public static void ReadCalibPointsFile(string path, out List<SemiPoint> real, out List<SemiPoint> ruler)
        {
            real = new List<SemiPoint>();
            ruler = new List<SemiPoint>();

            if (!File.Exists(path))
                return;

            foreach (var line in File.ReadLines(path))
            {
                var l = line.Trim();
                if (string.IsNullOrEmpty(l)) continue;
                if (l.StartsWith("#")) continue;

                var sp = l.Split(',');
                if (sp.Length < 4) continue;

                real.Add(new SemiPoint(
                    double.Parse(sp[0]),
                    double.Parse(sp[1])
                ));
                ruler.Add(new SemiPoint(
                    double.Parse(sp[2]),
                    double.Parse(sp[3])
                ));
            }
        }
    }
}
