/*
 * Copyright (c)  2017 Caipi Labs .
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * @author Nathanael BRAUN
 *
 * Date: 29/05/2017
 * Time: 10:50
 */
import rescope, {Store} from "rescope";
import xhr from "xhr";
import isString from "isstring";
import url from "jsx/utils/url";
// import {getBoundingBox} from "jsx/utils/geo";
// var kdbush           = require('kdbush');

var debounce = require('debounce');

import jsonp from 'jsonp';

export default class geoSearch extends Store {
    static use          = ["appParams", "appState"];
    static require      = ["appParams", "appState"];
    static initialState = {
        search  : '',
        results : []
    };

    constructor() {
        super(...arguments);
        this.__apply = debounce(this._apply.bind(this), 750)
    }

    clean() {
        this.setState({
                          search  : '',
                          results : []
                      })
    }


    apply( datas, {appParams : {mapZenApiKey, geonamesUserId, lang}, cPlaceId}, {search} ) {
        if ( !datas.cPlace && cPlaceId ) {
            return jsonp(`http://api.geonames.org/getJSON?geonameId=${
                             cPlaceId
                             }&lang=${
                             lang.toLowerCase()
                             }&username=${
                             geonamesUserId
                             }&type=json&inclBbox=true`,
                         // {},
                         ( e, r ) => {
                             if ( !e )
                                 this.stores.appState.setState({cPlace : r});
                             else
                                 this.stores.appState.setState({cPlaceId : null});
                         }
            )
        }
        this.__apply(...arguments)

        if ( !search )
            return {
                search  : '',
                results : []
            };
        return datas;
    }

    _apply( datas, {appParams : {mapZenApiKey, geonamesUserId, lang}}, {search} ) {
        //http://179-www-cartobusiness-accor-com-93121616.os.nextdeploy.publicis-nurun.com/#lang=FR&debug=true&cityPad=1
        let box       = bbox && bbox.toBBoxString().split(',').map(parseFloat),
            featTypes = [
                "PPLA"
                , "PPLC"
                , "PPLA1"
                , "PPLA2"
                ,
                "PPL"
                // , "ADM2"
                , "ADM1"
                // , "PPLA3"
                , "PCLI"
            ];// = box &&`&focus.rect.min_lon=${box[1]}&focus.rect.min_lat=${box[0]}&focus.rect.max_lon=${box[3]}&focus.rect.max_lat=${box[2]}`;


        if ( search && search.length > 1 ) {

            // bw / 2 - bh * dr / 1.5
            // xhr.get(`http://photon.komoot.de/api/?q=${
            //             encodeURI(search)
            //             }&limit=5&lang=${
            //             lang.toLowerCase()
            //             }`,

            jsonp(`http://api.geonames.org/searchJSON?name_startsWith=${
                      encodeURI(search)
                      }&searchlang=${
                      lang.toLowerCase()
                      }&username=${
                      geonamesUserId
                      }&type=json&orderby=population${featTypes.map(
                t => `&featureCode=${t}`)}&inclBbox=true&isNameRequired=true`,
                  ( e, r ) => {
                      // debugger;
                      let remap     = {},
                          countries = r.geonames.filter(place => (place.fcode == 'PCLI')),
                          cities    = r.geonames.filter(place => (place.fcode != 'PCLI'))
                              .reduce(
                                  ( r, place ) => {
                                      // debugger
                                      let key = place.name + '#' + place.countryCode + '#' + place.adminCode1;
                                      if ( remap[key] &&
                                          featTypes.indexOf(place.fcode) <
                                          featTypes.indexOf(remap[key].fcode) ) {

                                          r.splice(r.indexOf(remap[key]), 1);
                                          // if ( place.bbox.accuracyLevel < remap[key].bbox.accuracyLevel )
                                          //     place.bbox = remap[key].bbox;
                                          remap[key] = place;
                                          r.push(place);
                                      } else if ( !remap[key] ) {
                                          remap[key] = place;
                                          r.push(place);
                                      }
                                      return r;

                                  },
                                  []
                              ),
                          // .sort(
                          //     ( a, b ) => (b.population - a.population)),
                          suggests  = [
                              ...countries.slice(0, 5 - Math.min(3, cities.length)),
                              ...cities.slice(0, 5)
                          ].slice(0, 5)
                              .sort(function ( a, b ) {
                                  if ( a.name < b.name ) return -1;
                                  if ( a.name > b.name ) return 1;
                                  return 0;
                              })
                      ;

                      if ( this.state.search === search )
                          this.push(
                              {
                                  search  : search,
                                  results : suggests
                              }
                          )

                  }
            )
            return {
                searching : search,
                search    : '',
                results   : []
            };
        }
        return datas;
    }
}