export function getTicket(ticketId) {
  return fetch(`${eXo.env.portal.context}/${eXo.env.portal.rest}/customer-space/ticket/info/${ticketId}`, {
    method: 'GET',
    credentials: 'include',
  }).then((resp) => {
    if (resp && resp.ok) {
      return resp.json();
    } else {
      throw new Error('Error getting ticket data');
    }
  });
}
export function updateTicket(ticket, rate) {
  const param = rate ? '?rate=update' : '';
  return fetch(`${eXo.env.portal.context}/${eXo.env.portal.rest}/customer-space/ticket${param}`, {
    method: 'PUT',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(ticket, (key, value) => {
      if (value !== null) { return value; }
    }),
  }).then((resp) => {
    if (resp && resp.ok) {
      return resp.json();
    } else {
      throw new Error('Error updating ticket');
    }
  });
}

export function createTicket(ticket) {
  return fetch(`${eXo.env.portal.context}/${eXo.env.portal.rest}/customer-space/ticket`, {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(ticket, (key, value) => {
      if (value !== null) { return value; }
    }),
  }).then((resp) => {
    if (resp && resp.ok) {
      return resp.json();
    } else {
      throw new Error('Error saving ticket');
    }
  });
}

export function getTicketFlowStates(ticketFlowName) {
  return fetch(`${eXo.env.portal.context}/${eXo.env.portal.rest}/customer-space/ticket/flowstate/${ticketFlowName}`, {
    method: 'GET',
    credentials: 'include',
  }).then((resp) => {
    if (resp && resp.ok) {
      return resp.json();
    } else {
      throw new Error('Error getting ticket flow states data');
    }
  });
}

