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

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

  return {
    name: 'CloudronModel',
    async languages() {
      let error, result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/cloudron/languages`, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

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

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

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

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

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

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

export default {
  create,
};
