(function (global) {
  global.ARQ = global.ARQ || {};
  ARQ.storage = {
    get: function (key) {
      try {
        var r = localStorage.getItem(key);
        return r ? JSON.parse(r) : null;
      } catch (e) { return null; }
    },
    set: function (key, val) {
      try { localStorage.setItem(key, JSON.stringify(val)); } catch (e) {}
    },
    apiJson: function (action, opts) {
      opts = opts || {};
      var url = ARQ.config.apiUrl(action, opts.query);
      var conf = {
        method: opts.method || 'GET',
        headers: { 'Accept': 'application/json' },
      };
      if (opts.body != null) {
        conf.headers['Content-Type'] = 'application/json';
        conf.body = typeof opts.body === 'string' ? opts.body : JSON.stringify(opts.body);
      }
      return fetch(url, conf).then(function (r) {
        return r.text().then(function (t) {
          var j = null;
          try { j = JSON.parse(t); } catch (e) {
            return Promise.reject(new Error('Respuesta no JSON'));
          }
          return j;
        });
      });
    },
    apiForm: function (action, formData) {
      return fetch(ARQ.config.apiUrl(action), {
        method: 'POST',
        body: formData,
      }).then(function (r) { return r.json(); });
    },
  };
})(typeof window !== 'undefined' ? window : this);
