using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;

using Spherical;
using Spherical.IO;

namespace HST
{
    class Program
    {
        static void Main(string[] args)
        {
            // load region from file
            Console.Out.WriteLine("Loading from GZIP stream...");
            MemoryStream strm = new MemoryStream(Properties.Resources.acs_wfc_boundary_M101_edit_txt, false);
            GZipStream gzip = new GZipStream(strm, CompressionMode.Decompress);
            StreamReader rdr = new StreamReader(gzip);
            DateTime start = DateTime.Now;
            Region hst = ReadAcs(rdr);
            Console.Out.WriteLine(" - done in {0}", DateTime.Now - start);
            rdr.Close(); rdr.Dispose(); gzip.Close(); gzip.Dispose(); strm.Close(); strm.Dispose();
            Console.Out.WriteLine("# of convexes: {0}", hst.ConvexList.Count);

            BinWriter bin = new BinWriter(@"C:\Temp\AcsWfcM101e.bin");
            bin.Write(hst);
            bin.Close();

            Console.Out.WriteLine("Computing patches...");
            start = DateTime.Now;
            hst.Simplify(true, Const.Tolerance, Const.MaximumIteration, true);
            Console.Out.WriteLine(" - done in {0}", DateTime.Now - start);

            Console.Out.WriteLine("Computing area...");
            start = DateTime.Now;
            Console.Out.WriteLine("Area: {0} sq.deg.", hst.Area);
            Console.Out.WriteLine(" - done in {0}", DateTime.Now - start);
        }

        static private Region ReadAcs(StreamReader rdr)
        {
            char[] cma = new char[] { ',' };
            char[] spc = new char[] { ' ' };

            Region reg = new Region(1650);
            string line, trim;
            while ((line = rdr.ReadLine()) != null)
            {
                trim = line.Trim().Replace("J2000", " ");
                string[] t = trim.Split(cma);
                List<Cartesian> pts = Convex.ParsePoly(t[5]);
                Convex c = new Convex(pts, PointOrder.Safe);
                reg.Add(c); 
            }
            return reg;
        }

        static private Region ReadWfpc2(StreamReader rdr)
        {
            char[] cma = new char[] { ',' };
            char[] spc = new char[] { ' ' };

            Region reg = new Region("Hubble Space Telescope Pointings", 461400);
            string line, trim;
            while ((line = rdr.ReadLine()) != null)
            {
                trim = line.Trim().Replace("J2000", " ");
                string[] t = trim.Split(cma, 5);
                for (int i = 1; i < t.Length; i++)
                {
                    List<Cartesian> pts = Convex.ParsePoly(t[i]);
                    Convex c = new Convex(pts, PointOrder.Safe);
                    c.Name = String.Format("{0}-{1}", t[0].Trim(), i);
                    reg.Add(c);
                }
            }
            return reg;
        }

    }
}
