using System;
using System.Linq;
using System.Web.Mvc;
using CountryStateApplication.Models;

namespace CountryStateApplication.Controllers
{
    public class AddressController : Controller
    {
        private IAddressRepository _repository;

        public AddressController() : this(new AddressRepository())
        {
        }

        public AddressController(IAddressRepository repository)
        {
            _repository = repository;
        }


        public ActionResult Index()
        {
            AddressModel model = new AddressModel();
            model.AvailableCountries.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
            var countries = _repository.GetAllCountries();
            foreach (var country in countries)
            {
                model.AvailableCountries.Add(new SelectListItem()
                {
                    Text = country.Name,
                    Value = country.Id.ToString()
                });
            }
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetStatesByCountryId(string countryId)
        {            
            if (String.IsNullOrEmpty(countryId))
            {
                throw new ArgumentNullException("countryId");
            }
            int id = 0;
            bool isValid = Int32.TryParse(countryId, out id);           
            var states = _repository.GetAllStatesByCountryId(id);
            var result = (from s in states
                         select new
                         { 
                             id = s.Id, 
                             name = s.Name 
                         }).ToList();           

            return Json(result, JsonRequestBehavior.AllowGet);
        }

    }
}
