/*
 * This file is part of vospace-ui
 * Copyright (C) 2021 Istituto Nazionale di Astrofisica
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
const BASE_API_URL = process.env.VUE_APP_API_BASE_URL;

import axios from 'axios';
import store from '../../store';
import main from '../../main';

function apiRequest(options, showLoading = true, handleValidationErrors = false) {
  if (showLoading) {
    store.commit('setLoading', true);
  }
  return new Promise((resolve, reject) => {
    axios(options)
      .then(response => {
        if (response.status === 204) {
          resolve({});
        } else {
          resolve(response.data);
        }
        if (showLoading) {
          store.commit('setLoading', false);
        }
      })
      .catch(error => {
        store.commit('setLoading', false);
        if (handleValidationErrors && error.response && error.response.status === 400) {
          reject(error.response.data);
        } else {
          main.showError(getErrorMessage(error));
        }
      });
  });
}

function getErrorMessage(error) {
  if (error.response && error.response.data && error.response.data.message) {
    return error.response.data.message;
  } else if (error.message) {
    return error.message;
  } else {
    return 'Unknown error';
  }
}

function escapePath(path) {
  return path.split('/').map(p => encodeURIComponent(p)).join('/');
}

export default {
  getNode(path, loading) {
    let url = BASE_API_URL + 'nodes/' + escapePath(path);
    return apiRequest({
      method: 'GET',
      url: url,
      withCredentials: true,
      headers: {
        'Cache-Control': 'no-cache'
      }
    }, (typeof loading !== 'undefined') ? loading : true, true);
  },
  loadJobs() {
    let url = BASE_API_URL + 'jobs';
    return apiRequest({
      method: 'GET',
      url: url,
      withCredentials: true,
      headers: {
        'Cache-Control': 'no-cache'
      }
    }, false, true);
  },
  getUserInfo() {
    let url = BASE_API_URL + 'user';
    return apiRequest({
      method: 'GET',
      url: url,
      withCredentials: true,
      headers: {
        'Cache-Control': 'no-cache'
      }
    }, false, false);
  },
  startAsyncRecallJob(paths) {
    let url = BASE_API_URL + 'recall';
    return apiRequest({
      method: 'POST',
      url: url,
      withCredentials: true,
      headers: {
        'Cache-Control': 'no-cache'
      },
      data: paths
    });
  },
  createFolder(path, newFolderName) {
    let url = BASE_API_URL + 'folder';
    return apiRequest({
      method: 'POST',
      url: url,
      withCredentials: true,
      headers: {
        'Cache-Control': 'no-cache'
      },
      data: {
        parentPath: path,
        name: newFolderName
      }
    });
  },
  prepareForUpload(path, files) {
    let url = BASE_API_URL + 'preupload';
    return apiRequest({
      method: 'POST',
      url: url,
      withCredentials: true,
      headers: {
        'Cache-Control': 'no-cache'
      },
      data: {
        parentPath: path,
        files: files
      }
    });
  },
  uploadFile(url, file) {
    let formData = new FormData();
    formData.append('file', file);
    return axios.put(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },
  deleteNodes(paths) {
    let url = BASE_API_URL + 'delete';
    return apiRequest({
      method: 'POST',
      url: url,
      withCredentials: true,
      headers: {
        'Cache-Control': 'no-cache'
      },
      data: paths
    }, true, true);
  },
  keepalive() {
    let url = BASE_API_URL + 'keepalive';
    return apiRequest({
      method: 'GET',
      url: url,
      withCredentials: true,
      headers: {
        'Cache-Control': 'no-cache'
      }
    }, false, false);
  },
  getSharingInfo() {
    let url = BASE_API_URL + 'sharing';
    return apiRequest({
      method: 'GET',
      url: url,
      withCredentials: true,
      headers: {
        'Cache-Control': 'no-cache'
      }
    }, true, true);
  },
  setNodeGroups(data) {
    let url = BASE_API_URL + 'sharing';
    return apiRequest({
      method: 'POST',
      url: url,
      withCredentials: true,
      headers: {
        'Cache-Control': 'no-cache'
      },
      data
    }, true, true);
  },
  moveNode(data) {
    let url = BASE_API_URL + 'move';
    return apiRequest({
      method: 'POST',
      url: url,
      withCredentials: true,
      headers: {
        'Cache-Control': 'no-cache'
      },
      data
    }, true, true);
  }
}