// Ember!
import Ember from 'ember';

// Merge method
const { merge } = Ember;

/**
 * Default route for product search,
 * its based on the YeboSDK Query system
 * @todo Define some outlets like 'aggs', 'pagination', 'sort',
 *       to share more components in the search pages
 */
export default Ember.Mixin.create({
  /**
   * Default params
   * @todo Enable the user to add new actions without overwriting this
   */
  queryParams: {
    search: {
      refreshModel: true
    },
    page: {
      refreshModel: true
    },
    sort: {
      refreshModel: true
    }
  },

  /**
   * Default Sort
   */
  defaultSort: 'price-desc',

  /**
   * Products per page
   */
  perPage: 15,

  /**
   * Current aggregation
   */
  currentAggregation: null,

  /**
   * Selected aggregations used to generate
   * the next query
   */
  selectedAggs: {},

  /**
   * Flag to check if its necessary to fetch
   * aggregations again
   */
  refreshAggregations: true,

  /**
   * Route Model
   */
  model: function(params) {
    // Create a new query
    let query = new YeboSDK.Products();

    // Define the number of results per page
    query.perPage(this.get('perPage'));

    // Set the search
    if( params.search !== undefined )
      query.search(params.search);

    // Define the sort param
    let sortParam;

    // Check if the sort param exists
    if( params.sort !== undefined )
      sortParam = params.sort;
    else
      sortParam = this.get('defaultSort');

    // Sort options
    let sortOptions = sortParam.split('-');

    // Set the page
    query.sortBy(sortOptions[0], sortOptions[1]);

    // Set the page
    query.page(params.page);

    // Define the search rules
    this.searchRules(query, params);

    let defaultModel = {
      search: this.get('yebo.products').search(query),
      sortParam: sortParam,
      taxonomies: this.yebo.store.findAll('taxonomy')
    };

    // Make the searches
    return Ember.RSVP.hash(merge(this.searchModel(params), defaultModel));
  },

  /**
   * Clear the query params when the user leaves the search page
   */
  resetController(controller, isExiting, transition) {
    // Check if the user is leaving the page
    if (isExiting) {
      // Reset the page
      controller.set('page', 1);

      // Reset the search
      controller.set('search', undefined);

      // Reset the sort
      controller.set('sort', undefined);
    }
  },

  /**
   * Route actions
   * @todo Enable the user to add new actions without overwriting this
   */
  actions: {
    changePage: function(pageNumber) {
      // Change the page number
      this.transitionTo({ queryParams: { page: pageNumber } })
    },
    changeSort: function(sort) {
      // Change the sort
      this.transitionTo({ queryParams: { sort: sort } })
    }
  },

  /**
   * Generate the search rules and put it into the
   * query that is going to be used
   * @todo Enable this method to be async
   * @param {YeboSDK.Products} query The query that is being formed,
   *                           so new rules will be added into this new query.
   * @param {Object} params Parameters that come from the route
   * @return {void} This method does not return anything
   */
  searchRules(query, params) {
    // Do nothing
  },

  /**
   * This method enable the route to add info into the
   * model object that is returned
   * @param {Object} params Parameters that come from the route
   * @return {Object} This object will be merged into the default model
   *                  from the search, and it will processed by the
   *                  Ember.RSVP.Hash method
   */
  searchModel(params) {
    // As default return an empty object
    return {};
  }
});

@@ -1733,24 +1733,59 @@
     
-let defaultModel
+// Set the default promises%0A    let defaultPromises
  = %7B
@@ -1844,36 +1844,8 @@
 y),%0A
-      sortParam: sortParam,%0A
     
@@ -1897,114 +1897,963 @@
 my')
-%0A    %7D;%0A%0A    // Make the searches%0A    return Ember.RSVP.hash(merge(this.searchModel(params), defaultModel)
+,%0A      selectedAggs: this.get('selectedAggs')%0A    %7D;%0A%0A    // Check if its necessary to get the aggregations%0A    if( this.get('currentAggregation') === null %7C%7C this.get('refreshAggregations') )%0A      defaultPromises.aggs = query.aggregations();%0A    else%0A      defaultPromises.aggs = this.get('currentAggregation');%0A%0A    // Return a promise to the route%0A    return new Ember.RSVP.Promise((resolve, reject) =%3E %7B%0A      // Execute the default model promises%0A      Ember.RSVP.hash(defaultPromises).then((result) =%3E %7B%0A        // Set the current aggregation%0A        this.set('currentAggregation', result.aggs);%0A%0A        // Define the route model%0A        let routeModel = this.searchModel(params);%0A%0A        // Check if it is a promise%0A        if( routeModel.then === undefined )%0A          return resolve(merge(routeModel, result));%0A%0A        // Resolve the promise with the result%0A        routeModel.then((res) =%3E %7B resolve(merge(res, result)); %7D);%0A      %7D);%0A    %7D
 );%0A 
@@ -4381,38 +4381,34 @@
 arch
-, and it will processed by the
+. It can be a Promise that
 %0A   
@@ -4430,30 +4430,26 @@
     
-Ember.RSVP.Hash method
+returns an Object.
 %0A   

Store the currentAggregations to the route and enable the searchModel to be a promise