import { config, networkUtils, stringUtils } from '../../utils';

const { request } = networkUtils;
const { api, baseURL } = config;
const { sfs } = api;

export async function upload(api) {
  return request({
    url: sfs.upload.replace('{api}', api),
    method: 'post',
  });
}

export async function list(api, dataKey) {
  return request({
    url: sfs.list.replace('{api}', api),
    method: 'get',
    data: { dataKey },
  });
}

export async function remove(api, dataKey, fileHash) {
  return request({
    url: sfs.delete.replace('{api}', api),
    method: 'form',
    data: {
      dataKey,
      hash: fileHash,
    },
  });
}

export async function download(api, dataKey, fileHash) {
  return request({
    url: `${baseURL + sfs.download.replace('{api}', api)}`,
    method: 'get',
    data: {
      dataKey,
      hash: fileHash,
      'el-xsrf': localStorage.getItem('csrfToken'),
      _t: Date.parse(new Date()) / 1000,
    },
  });
}

export function getDownloadLink(itemHash, dataKey, tokenInfo) {
  return `${baseURL}${sfs.download}?${stringUtils.JSON2QueryString({
    hash: itemHash,
    dataKey,
    ...tokenInfo,
    'el-xsrf': localStorage.getItem('csrfToken'),
    _t: Date.parse(new Date()) / 1000,
  })}`;
}

export function batchDownload(packId) {
  const now = new Date().getTime();
  const token = localStorage.getItem('csrfToken');
  window.open(`${baseURL}/edp/sfs/pack?id=${packId}&el-xsrf=${token}&_t_=${now}`);
}
