using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebSamples.Repositories.Interfaces;
using Microsoft.SqlServer.Types;
using System.Data.SqlTypes;
using System.Globalization;

namespace WebSamples.Repositories
{
    public class GeoCityRepository : IGeoCityRepository
    {
        #region Private fields

        // Data context
        WygdayGeoDataContext ctx = new WygdayGeoDataContext();

        #endregion

        #region Public methods

        public IEnumerable<GeoPoint> GetAllCities()
        {
            throw new NotImplementedException();
        }

        public IEnumerable<GeoPoint> GetCitiesNearBy(double latitude, double longitude, int radius)
        {
            return this.ctx.GetCitiesNearBy(latitude, longitude, radius);
        }

        public IEnumerable<GeoPoint> GetCitiesBounded(double topLeftLat, double topLeftLong,
                                                      double botRightLat, double botRightLong)
        {
            // Create a polygon to easily get the WKT representation
            string polyWktFormat = "POLYGON(({1} {2}, {3} {2}, {3} {0}, {1} {0}, {1} {2}))";
            string polyGenerated = string.Format(polyWktFormat,
                topLeftLat.ToString(CultureInfo.InvariantCulture.NumberFormat),
                topLeftLong.ToString(CultureInfo.InvariantCulture.NumberFormat),
                botRightLat.ToString(CultureInfo.InvariantCulture.NumberFormat),
                botRightLong.ToString(CultureInfo.InvariantCulture.NumberFormat));

            //SqlGeography geog = SqlGeography.STPolyFromText(
            //    new System.Data.SqlTypes.SqlChars(
            //        new SqlString(
            //            polyGenerated
            //        )
            //    ), 
            //    4326
            //);

            return this.ctx.GetCitiesBoundedSpatial(polyGenerated);
        }
        #endregion
    }
}
