/*
 * Copyright 2018 ThoughtWorks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


const m        = require('mithril');
const $        = require('jquery');
const mrequest = require('helpers/mrequest');

function makeRequest({method, url, apiVersion, type, timeout = mrequest.timeout, payload, etag, contentType = false} = {}) {
  return $.Deferred(function () {
    const deferred = this;

    const jqXHR = $.ajax({
      method,
      url,
      data:       JSON.stringify(payload),
      timeout,
      beforeSend: (xhr) => {
        xhr.setRequestHeader('If-Match', etag);
        mrequest.xhrConfig.forVersion(apiVersion)(xhr);
      },
      contentType
    });

    const didFulfill = (data, _textStatus, jqXHR) => {
      if (type) {
        deferred.resolve(type.fromJSON(data, jqXHR));
      } else {
        deferred.resolve(data, _textStatus, jqXHR);
      }
    };

    jqXHR.then(didFulfill, deferred.reject);

    jqXHR.always(m.redraw);
  }).promise();

}

module.exports = class AjaxHelper {

  static GET({url, apiVersion, type, timeout = mrequest.timeout} = {}) {
    return makeRequest({method: 'GET', url, apiVersion, type, timeout});
  }

  static PUT({url, apiVersion, timeout = mrequest.timeout, payload, contentType = 'application/json'}) {
    return makeRequest({method: 'PUT', url, apiVersion, timeout, payload, contentType});
  }

  static POST({url, apiVersion, timeout = mrequest.timeout, payload, type, contentType = 'application/json'}) {
    return makeRequest({method: 'POST', url, apiVersion, timeout, type, payload, contentType});
  }

  static PATCH({url, apiVersion, timeout = mrequest.timeout, payload, type, etag, contentType = 'application/json'}) {
    return makeRequest({method: 'PATCH', url, apiVersion, timeout, payload, type, etag, contentType});
  }
};



@@ -1072,16 +1072,67 @@
 tHeader(
+%22GET%22 === method.toUpperCase() ? 'If-None-Match' : 
 'If-Matc
@@ -1574,17 +1574,16 @@
 elper %7B%0A
-%0A
   static
@@ -1637,16 +1637,22 @@
 .timeout
+, etag
 %7D = %7B%7D) 
@@ -1722,16 +1722,22 @@
  timeout
+, etag
 %7D);%0A  %7D%0A
@@ -1796,32 +1796,38 @@
 imeout, payload,
+ etag,
  contentType = '
@@ -1913,32 +1913,38 @@
 imeout, payload,
+ etag,
  contentType%7D);%0A
@@ -2012,24 +2012,30 @@
 ut, payload,
+ etag,
  type, conte
@@ -2146,16 +2146,22 @@
 payload,
+ etag,
  content

Add support for ETag to all methods in AjaxHelper