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

const changeHandlers = {};
const KEYS = {
  NAME: 'name',
  FOOTER: 'footer',
  BACKGROUND: 'background', // only returns a URI with cachebusting
  AVATAR: 'avatar',         // only returns a URI with cachebusting
};

function notifyChange(key, value) {
  const listener = changeHandlers[key] || [];
  listener.forEach(h => h(value));
}

// key is one of KEYS
function onChange(key, handler) {
  if (typeof handler !== 'function') return;

  if (!changeHandlers[key]) changeHandlers[key] = [];

  changeHandlers[key].push(handler);
}

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

  return {
    async getFooter() {
      let error, result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/branding/footer`, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

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

      notifyChange(KEYS.FOOTER, footer);

      return [null];
    },
    async setName(name) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/branding/cloudron_name`, { name }, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

      notifyChange(KEYS.NAME, name);

      return [null];
    },
    async unsetBackground() {
      let error, result;
      try {
        result = await fetcher.del(`${API_ORIGIN}/api/v1/branding/cloudron_background`, null, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

      notifyChange(KEYS.BACKGROUND, `${API_ORIGIN}/api/v1/cloudron/background?ts=${Date.now()}`);

      return [null];
    },
    async setBackground(image) {
      // Blob type if object
      const fd = new FormData();
      if (image) fd.append('background', image);

      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/branding/cloudron_background`, fd, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

      notifyChange(KEYS.BACKGROUND, `${API_ORIGIN}/api/v1/cloudron/background?ts=${Date.now()}`);

      return [null];
    },
    async setAvatar(image) {
      // Blob type if object
      const fd = new FormData();
      fd.append('avatar', image);

      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/branding/cloudron_avatar`, fd, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

      notifyChange(KEYS.AVATAR, `${API_ORIGIN}/api/v1/cloudron/avatar?ts=${Date.now()}`);

      return [null];
    },
  };
}

export default {
  KEYS,
  onChange,
  create,
};
