import Ember from 'ember';

const { typeOf, inject } = Ember;

export default Ember.Mixin.create({
  paramsRelay: inject.service(),

  beforeModel() {
    var paramsRelay = this.get('paramsRelay');
    var routeName = this.routeName || this.router.currentRouteName;
    var controller = this.controllerFor(routeName);

    if (!this._eqpSubscribed) {
      paramsRelay.autoSubscribe(controller);
      this._eqpSubscribed = true;
    }

    // Set initial QPs since action fires first
    if (this._initialQps) {
      Ember.run.schedule('afterRender', this, () => {
        paramsRelay.setParams(this._initialQps);
        this._initialQps = undefined;
      });
    }

    return this._super(...arguments);
  },

  subscribeParam(name, cb) {
    var paramsRelay = this.get('paramsRelay');

    paramsRelay.subscribe(name, cb);
  },

  unsubscribeParam(name, cb) {
    var paramsRelay = this.get('paramsRelay');

    paramsRelay.unsubscribe(name, cb);
  },

  actions: {
    queryParamsDidChange: function eqpQueryParamsDidChange(changed) {
      var paramsRelay = this.get('paramsRelay');
      var routeName = this.routeName || this.router.currentRouteName;
      var params = this.paramsFor(routeName);
      var changedKeys = Object.keys(changed);
      var deserialized = changedKeys.reduce((res, key) => {
        let raw = params[key];
        let value = this.deserializeQueryParam(changed[key], key, typeOf(raw));

        res[key] = value;
        return res;
      }, {});

      if (changedKeys.length && this._eqpSubscribed) {
        paramsRelay.setParams(deserialized);
      } else if (changedKeys.length && !this._eqpSubscribed) {
        this._initialQps = deserialized;
      }

      return this._super(...arguments);
    }
  }
});

@@ -54,16 +54,51 @@
 = Ember;
+%0Aconst arrRegex = /%5E%22?%5C%5B.*,*%5C%5D%22?$/;
 %0A%0Aexport
@@ -1372,16 +1372,110 @@
 s%5Bkey%5D;%0A
+        let changedRaw = changed%5Bkey%5D;%0A        let normalized = normalizeArrayQp(changedRaw);%0A
         
@@ -1517,26 +1517,63 @@
 ram(
-changed%5B
+normalized, 
 key
-%5D
 , 
-key,
+normalized.match(arrRegex) ? 'array' :
  typ
@@ -1758,24 +1758,52 @@
  %7D else if (
+!paramsRelay.hasParams() && 
 changedKeys.
@@ -1936,12 +1936,160 @@
   %7D%0A  %7D%0A
-
 %7D);%0A
+%0Afunction normalizeArrayQp(val) %7B%0A  if (val.match(/%5E%22%5C%5B.*,*%5C%5D%22$/)) %7B%0A    try %7B%0A      return JSON.parse(val);%0A    %7D catch(e) %7B%7D%0A  %7D%0A%0A  return val;%0A%7D%0A

Normalize string array values