import BaseIntegrationModule from './base';

const GetResponse = BaseIntegrationModule.extend({
  getName() {
    return 'getresponse';
  },

  onElementChange(setting) {
    switch (setting) {
      case 'getresponse_api_key_source':
      case 'getresponse_custom_api_key':
        this.onApiUpdate();
        break;

      case 'getresponse_list':
        this.onGetResponseListUpdate();
        break;
    }
  },

  onApiUpdate() {
    const self = this;
    const customKeyControl = self.getEditorControlView('getresponse_custom_api_key');
    const globalKeyControl = self.getEditorControlView('getresponse_api_key_source');

    if (!customKeyControl || !globalKeyControl) {
      return;
    }

    // If using a non-default global key but no custom key → clear list
    if ('default' !== globalKeyControl.getControlValue() && '' === customKeyControl.getControlValue()) {
      self.updateOptions('getresponse_list', []);
      const listControl = self.getEditorControlView('getresponse_list');
      if (listControl) listControl.setValue('');
      return;
    }

    // Add a spinner to the list control
    self.resetControlIndicators('getresponse_list');
    self.addControlSpinner('getresponse_list');

    const cacheKey = this.getCacheKey({
      type: 'lists',
      controls: [customKeyControl.getControlValue(), globalKeyControl.getControlValue()]
    });

    // Fetch GetResponse lists
    self.getGetResponseCache('lists', 'lists', cacheKey)
      .done(function (data) {
        self.updateOptions('getresponse_list', data.lists);
        self.updateGetResponseList();
      })
      .fail(function (error) {
        self.addControlError('getresponse_list', error);
      })
      .always(function () {
        self.removeControlSpinner('getresponse_list');
      });
  },

  onGetResponseListUpdate() {
    // Just refresh field mapping when list changes
    this.updateGetResponseList();
  },

  updateGetResponseList() {
    const self = this;
    const listControl = self.getEditorControlView('getresponse_list');

    if (!listControl || !listControl.getControlValue()) {
      return;
    }

    // Add spinner to fields map
    self.resetControlIndicators('getresponse_fields_map');
    self.addControlSpinner('getresponse_fields_map');

    // Fetch fields for selected list
    const cacheKey = this.getCacheKey({
      type: 'fields',
      controls: [listControl.getControlValue()]
    });

    self.getGetResponseCache('fields', 'get_fields', cacheKey, {
      getresponse_list: listControl.getControlValue()
    })
      .done(function (data) {
        const fieldsMap = self.getEditorControlView('getresponse_fields_map');
        if (fieldsMap && data.fields) {
          fieldsMap.updateMap(data.fields);
        }
      })
      .fail(function (error) {
        self.addControlError('getresponse_fields_map', error);
      })
      .always(function () {
        self.removeControlSpinner('getresponse_fields_map');
      });
  },

  // ✅ Backward compatibility alias (some versions still call this name)
  updatGetResonseList() {
    this.updateGetResponseList();
  },

  getGetResponseCache(type, action, cacheKey, requestArgs, immediately = false) {
    if (_.has(this.cache[type], cacheKey)) {
      const data = {};
      data[type] = this.cache[type][cacheKey];
      return jQuery.Deferred().resolve(data);
    }

    requestArgs = _.extend({}, requestArgs, {
      service: 'getresponse',
      getresponse_action: action,
      api_key: this.getEditorControlView('getresponse_api_key_source').getControlValue(),
      custom_api_key: this.getEditorControlView('getresponse_custom_api_key').getControlValue()
    });

    return this.fetchCache(type, cacheKey, requestArgs, immediately);
  },

  onSectionActive() {
    BaseIntegrationModule.prototype.onSectionActive.apply(this, arguments);
    this.onApiUpdate();
  }
});

export default GetResponse;
