
import { fetcher } from '@cloudron/pankow';
import { sleep } from '@cloudron/pankow/utils';
import { API_ORIGIN } from '../constants.js';

function create() {
  const accessToken = localStorage.token;

  return {
    async wait(id, progressHandler = function () {}) {
      while(true) {
        let result;
        try {
          result = await fetcher.get(`${API_ORIGIN}/api/v1/tasks/${id}`, { access_token: accessToken });
        } catch (e) {
          return [e];
        }

        if (!result.body.active) return [result.body.error, result.body.result];

        progressHandler(result.body);

        await sleep(2000);
      }
    },
    async getByType(type) {
      let error, result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/tasks`, { type, access_token: accessToken });
      } catch (e) {
        error = e;
      }

      if (error || result.status !== 200) return [error || result];
      return [null, result.body.tasks];
    },
    async get(id) {
      let error, result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/tasks/${id}`, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

      if (error || result.status !== 200) return [error || result];
      return [null, result.body];
    },
    async stop(id) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/tasks/${id}/stop`, {}, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

      if (error || result.status !== 204) return [error || result];
      return [null];
    },
  };
}

export default {
  create,
};
