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

using SphericalLib;

namespace Quest
{
    class Program
    {
        static void Main(string[] args)
        {
            // load region from file
            Console.Out.WriteLine("Loading from GZIP stream...");
            MemoryStream strm = new MemoryStream(Properties.Resources.JBframes_txt, false);
            GZipStream gzip = new GZipStream(strm, CompressionMode.Decompress);
            StreamReader rdr = new StreamReader(gzip);
            DateTime start = DateTime.Now;
            Region r = Read(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}", r.convexList.Count);

            Cartesian center = new Cartesian(180, 0);
            r.Intersect(new Halfspace(center, 0));

            Console.Out.WriteLine("Computing area...");
            start = DateTime.Now;
            SuperRegion s = new SuperRegion(r, false, false);
            Console.Out.WriteLine(" - done in {0}", DateTime.Now - start);
            Console.Out.WriteLine("Area: {0}", s.area);

            double scale = 100;

            SphericalVisualizer.RegionCanvas canvas = new SphericalVisualizer.RegionCanvas
                (center.RA, center.Dec, "STR", 1200, 1200, 3600 / scale, false);
            canvas.DrawRegion(s, System.Drawing.Color.Yellow, 1);
            canvas.drawLabel(String.Format("Center (RA, Dec): {0:n}, {1:n} deg.", center.RA, center.Dec));
            canvas.drawLabel(String.Format("Area: {0:n} sq.deg.", s.area));
            try { canvas.drawGrid(); }
            catch { };

            canvas.Image.Save(@"c:\temp\quest.gif", System.Drawing.Imaging.ImageFormat.Gif);
        }

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

            Region reg = new Region("JB", 200000);
            List<Cartesian> pts = new List<Cartesian>(4);
            string line, trim;
            
            while ((line = rdr.ReadLine()) != null)
            {
                trim = line.Trim();
                string[] tok = trim.Split(spc);
                double ra, dec;
                for (int i = 0; i < tok.Length; i+=2)
                {
                    ra = double.Parse(tok[i]);
                    dec = double.Parse(tok[i + 1]);
                    pts.Add(new Cartesian(ra, dec));
                }
                reg.convexList.Add(new Convex(pts, PointOrder.Safe));
                pts.Clear();
            }
            return reg;
        }

    }
}
