using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebDataEntities;
using WebDataHelper.Translators;

namespace WebDataHelper
{
    public class GeoDataHelper
    {
        #region Private fields

        GeoPointDataContext ctx = new GeoPointDataContext();

        #endregion

        #region Data request methods

        public List<GeoPoint> GetNearPoints(string wkt, int distance)
        {
            return ctx.GetNearPoints(wkt, distance).Select(p => GeoPointTranslator.ToGeoPoint(p)).ToList();
        }

        public List<GeoPoint> GetNearPoints(List<GeoPoint> points, int distance)
        {

            List<GeoPoint> results = new List<GeoPoint>();
            try
            {
                string wkt = this.getTextWkt(points);
                if (!string.IsNullOrEmpty(wkt))
                    results = ctx.GetNearPoints(wkt, distance).Select(p => GeoPointTranslator.ToGeoPoint(p)).ToList();
            }
            catch (Exception)
            {
                // TODO: catch
            }

            return results;
        }

        #endregion

        #region Private methods

        string getTextWkt(List<GeoPoint> points)
        {
            string wktTemp = string.Empty;

            string formatWkt = "{0} {1},";
            foreach (GeoPoint curPoint in points)
            {
                wktTemp += string.Format(formatWkt,
                                            curPoint.Longitude.ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat),
                                            curPoint.Latitude.ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat));
            }

            return wktTemp.Substring(0, wktTemp.Length - 1);    // remove the last comma
        }

        #endregion

    }
}
