var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

import { CustomField } from './CustomField';

var toSettingsRequest = function toSettingsRequest(instanceId, appId, name, value) {
  return {
    method: "PUT",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    url: 'apps/' + instanceId + '/state/app:' + appId + '/' + name,
    data: { value: value }
  };
};

/**
 * @param {string} instanceId
 * @param {CustomField} customField
 * @return {{method: string, headers: {Accept: string, Content-Type: string}, url: string, body}}
 */
var toCustomFieldRequest = function toCustomFieldRequest(instanceId, customField) {
  var urlMap = {
    'ticket': '/ticket_custom_fields',
    'organization': '/organization_custom_fields',
    'person': '/person_custom_fields'
  };
  var url = urlMap[customField.attachedTo];

  if (!url) {
    throw new Error('could not map custom field to create field request');
  }

  return {
    method: "POST",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    url: url,
    data: {
      title: customField.title,
      is_enabled: true,
      is_user_enabled: false,
      is_agent_field: true,
      alias: customField.getQualifiedAlias(instanceId),
      handler_class: customField.getHandlerClass()
    }
  };
};

export var AppInstallerService = function () {
  /**
   * @param {{post: function, put: function}}  api
   */
  function AppInstallerService(_ref) {
    var api = _ref.api;

    _classCallCheck(this, AppInstallerService);

    this.props = { api: api };
  }

  /**
   * @param instanceId
   * @param {Array} changes
   * @return {Array}
   */


  _createClass(AppInstallerService, [{
    key: 'createInstallTasks',
    value: function createInstallTasks(instanceId, changes) {
      var _this = this;

      var tasks = [];
      var customFieldsAdditions = changes.filter(function (change) {
        return change.type === 'add' && change.module === 'customFields';
      }).map(function (change) {
        return change.value;
      });

      if (customFieldsAdditions.length) {
        tasks.push(function () {
          return _this.addCustomFields(instanceId, { customFields: customFieldsAdditions });
        });
      }

      tasks.push(function () {
        return _this.setInstalled(instanceId, { status: true });
      });
      return tasks;
    }

    /**
     * @param {string} instanceId
     * @param {string} appId
     * @param {{}} values
     * @return {Promise.<{}>}
     */

  }, {
    key: 'saveSettings',
    value: function saveSettings(instanceId, appId, values) {
      var url = 'batch';
      var requests = Object.keys(values).reduce(function (acc, key) {
        acc[key] = toSettingsRequest(instanceId, appId, key, values[key]);
        return acc;
      }, {});

      if (Object.keys(requests).length > 0) {
        return this.props.api.post(url, { requests: requests }).then(function () {
          return values;
        });
      }

      return Promise.resolve(values);
    }

    /**
     * @param {String} instanceId
     * @param {[]} customFields
     * @return {Promise.<[]>}
     */

  }, {
    key: 'addCustomFields',
    value: function addCustomFields(instanceId, _ref2) {
      var customFields = _ref2.customFields;

      if (customFields instanceof Array && customFields.length > 0) {
        var url = 'batch';
        var requests = customFields.map(function (props) {
          return new CustomField(props);
        }).reduce(function (acc, customField) {
          acc[customField.alias] = toCustomFieldRequest(instanceId, customField);
          return acc;
        }, {});
        return this.props.api.post(url, { requests: requests }).then(function () {
          return customFields;
        });
      }

      return Promise.resolve(customFields);
    }

    /**
     * @param instanceId
     * @param {boolean} status
     * @return {Promise.<{status: *}>}
     */

  }, {
    key: 'setInstalled',
    value: function setInstalled(instanceId, _ref3) {
      var status = _ref3.status;

      return this.props.api.put('apps/' + instanceId, { is_installed: status }).then(function () {
        return { status: status };
      });
    }
  }]);

  return AppInstallerService;
}();