using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AjaxDestinations.Models;
using System.Threading;

namespace AjaxDestinations.Controllers
{
    public class DatasourcesController : Controller
    {
        //
        // GET: /Datasources/
        private gcutourswmEntities db = new gcutourswmEntities();

        public ActionResult Locations()
        {
            var locations = (from p in db.Packages
                            select p.location).Distinct();

            return Json(locations,JsonRequestBehavior.AllowGet);
        }

        public ActionResult TourDates(string location)
        {
            var tourDates = from t in db.Tours
                            where t.Package.location == location
                            select t.departuredate;

            return Json(tourDates, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Packages()
        {
            var packages = from p in db.Packages
                           select new
                                      {
                                          packageID = p.packageID,
                                          packagename = p.packagename
                                      };

            return Json(packages, JsonRequestBehavior.AllowGet);
        }

        public ActionResult PackageDetails(int packageID)
        {
            db.ContextOptions.LazyLoadingEnabled = false;

            var package = (from p in db.Packages
                          where p.packageID == packageID
                          select p).FirstOrDefault();

            return Json(package, JsonRequestBehavior.AllowGet);
        }

        public JsonResult AddUser(User user)
        {
            Thread.Sleep(3000);    // keep 'em waiting for a bit...
            try
            {
                db.AddToUsers(user);
                db.SaveChanges();

                var saveduser = (from u in db.Users
                                 where u.username == user.username
                                 select u).FirstOrDefault();

                return Json(String.Format("Saved user: {0} {1}", user.firstname, user.lastname));
            }
            catch
            {
                return Json("It didnae work - not saved");
            }
        }

        public ActionResult LocationsIframe()
        {
            var locations = (from p in db.Packages
                             select p.location).Distinct().ToList();

            return View(locations);
        }

        public ActionResult IP2Geo(string address)
        {
            var client = new IP2GeoService.P2GeoSoapClient();
            var result = client.ResolveIP(address, "0");
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}
