$ = jQuery
context = window
rest = window.JK.Rest()
logger = context.JK.logger

@LocationStore = Reflux.createStore(
  {
    listenables: @LocationActions
    countries: {}

    init: ->
      # Register with the app store to get @app
      this.listenTo(context.AppStore, this.onAppInit)

    changed: () ->
      @trigger(@countries)

    onSelectCountry: (country) ->
      @loadRegions(country)

    onSelectRegion: (country, region) ->
      @loadCities(country, region)


    onLoad: () ->

      # avoid double-loads
      if Object.keys(@countries).length == 0
        rest.getCountries().done ((response) =>
          countries = response.countriesx
          if Object.keys(@countries).length == 0
            for country in countries
              name = country.countryname
              if !name?
                name = country.countrycode
              @countries[country.countrycode] = {name: name, regions:null}

            @loadRegions('US')
        )

    loadRegions: (loadForCountry) ->
      if loadForCountry == null
        return

      country = @countries[loadForCountry]

      if !country?
        logger.warn("country is null in searching for: " + loadForCountry)
        return

      regions = country.regions

      # avoid double-loads
      if regions == null
        rest.getRegions({country: loadForCountry}).done ((countriesRegions) =>
          regions = country.regions
          if regions == null
            regions = []
            country.regions = regions

          if regions.length > 0
            console.log("bailing on dup load of regions")
            return

          for region in countriesRegions.regions

            id = region.region
            name = region.name
            if !name?
              name = region.region

            regions.push({id: id, name: name, cities:[]})

          @changed()
        )

    loadCities: (loadForCountry, region) ->
      console.log("load cities",loadForCountry, region)
      if loadForCountry == null || region == null
        logger.warn('country or region is null', loadForCountry, region)

      country = @countries[loadForCountry]

      if !country?
        logger.warn("country is null in searching for: " + loadForCountry)
        return

      regions = country.regions

      # avoid double-loads
      for checkRegion in regions
        if checkRegion.id == region
          if checkRegion.cities.length == 0
            rest.getCities({ country: loadForCountry, region: region })
            .done((cities)  =>
              logger.debug('cities loaded', cities)
              checkRegion.cities = cities.cities
              @changed()
            )
          break

    onAppInit: (@app) ->

  }
)
