function authHeaders() {
  return window.getAuthHeaders ? window.getAuthHeaders() : { 'Content-Type': 'application/json' };
}

function json(response) {
  return response.json().catch(function() { return {}; });
}

export function listActive() {
  return fetch('/api/notes', { headers: authHeaders(), credentials: 'include' }).then(json);
}

export function listTrash() {
  return fetch('/api/notes/trash', { headers: authHeaders(), credentials: 'include' }).then(json);
}

export function saveNote(id, payload) {
  var isNew = id == null;
  return fetch(isNew ? '/api/notes' : '/api/notes/' + id, {
    method: isNew ? 'POST' : 'PUT',
    headers: authHeaders(),
    credentials: 'include',
    body: JSON.stringify(payload || {})
  }).then(json);
}

export function saveNoteKeepalive(id, payload) {
  var isNew = id == null;
  return fetch(isNew ? '/api/notes' : '/api/notes/' + id, {
    method: isNew ? 'POST' : 'PUT',
    keepalive: true,
    credentials: 'include',
    headers: authHeaders(),
    body: JSON.stringify(payload || {})
  });
}

export function restore(id) {
  return fetch('/api/notes/' + id + '/restore', {
    method: 'POST',
    credentials: 'include',
    headers: authHeaders()
  }).then(json);
}

export function hardDelete(id) {
  return fetch('/api/notes/' + id + '?hard=1', {
    method: 'DELETE',
    credentials: 'include',
    headers: authHeaders()
  }).then(json);
}

export function emptyTrash() {
  return fetch('/api/notes/trash/empty', {
    method: 'POST',
    credentials: 'include',
    headers: authHeaders()
  }).then(json);
}

export function moveToTrash(id) {
  return fetch('/api/notes/' + id, {
    method: 'DELETE',
    headers: authHeaders(),
    credentials: 'include'
  }).then(json);
}

export function noteFromVoice(payload) {
  return fetch('/api/notes/from-voice', {
    method: 'POST',
    credentials: 'include',
    headers: authHeaders(),
    body: JSON.stringify(payload || {})
  }).then(json);
}
