/*
 * This file is part of the Meeds project (https://meeds.io/).
 * 
 * Copyright (C) 2020 - 2022 Meeds Association contact@meeds.io
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
import {REST_ROOT_PATH} from './Constants';

export function getTenants(status, limit, includeCompleted) {
  const formData = new FormData();
  formData.append('status', status || '');
  formData.append('includeCompleted', includeCompleted || false);
  formData.append('limit', limit || 5);
  const urlParams = new URLSearchParams(formData).toString();

  return fetch(`${REST_ROOT_PATH}/tenants?${urlParams}`, {
    method: 'GET',
    credentials: 'include',
  }).then(resp => {
    if (resp && resp.ok) {
      return resp.json();
    } else {
      throw new Error('Error retrieving Tenants list from server', resp);
    }
  }).then(deeds => {
    const promises = [];
    if (deeds?.deeds) {
      Object.keys(deeds.deeds)
        .forEach(provisioningStatus => {
          const tenants = deeds.deeds[provisioningStatus];
          if (tenants?.length) {
            tenants.forEach(tenant => {
              promises.push(refreshDeedTask(tenant));
            });
          }
        });
    }
    return Promise.all(promises)
      .then(() => deeds);
  });
}

export function saveTenantStatus(nftId, tenantStatus) {
  const formData = new FormData();
  formData.append('tenantStatus', tenantStatus);
  return fetch(`${REST_ROOT_PATH}/tenants/${nftId}`, {
    method: 'PATCH',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams(formData).toString(),
  }).then(resp => {
    if (!resp || !resp.ok) {
      throw new Error('Error saving Tenant Status on server', resp);
    }
  });
}

export function refreshDeedTask(deed) {
  if (deed?.properties?.currentTaskId) {
    return getTask(deed?.properties?.currentTaskId)
      .then(task => {
        deed.task = task;
        return task;
      });
  } else {
    deed.task = null;
    return Promise.resolve(null);
  }
}

export function getTask(taskId) {
  return fetch(`${eXo.env.portal.context}/${eXo.env.portal.rest}/tasks/${taskId}`, {
    method: 'GET',
    credentials: 'include',
  }).then(resp => {
    if (resp && resp.ok) {
      return resp.json();
    } else {
      throw new Error('Error retrieving Task details from server', resp);
    }
  });
}

