import assert from 'node:assert';
import BoxError from './boxerror.js';
import constants from './constants.js';
import cron from './cron.js';
import moment from 'moment-timezone';
import settings from './settings.js';
import translations from './translations.js';


async function getStatus() {
    return {
        version: constants.VERSION,
    };
}

async function getTimeZone() {
    const tz = await settings.get(settings.TIME_ZONE_KEY);
    return tz || 'UTC';
}

async function setTimeZone(tz) {
    assert.strictEqual(typeof tz, 'string');

    if (moment.tz.names().indexOf(tz) === -1) throw new BoxError(BoxError.BAD_FIELD, 'Bad timeZone');

    await settings.set(settings.TIME_ZONE_KEY, tz);
    await cron.handleTimeZoneChanged(tz);
}

async function getLanguage() {
    const value = await settings.get(settings.LANGUAGE_KEY);
    return value || 'en';
}

async function setLanguage(language) {
    assert.strictEqual(typeof language, 'string');

    const languages = await translations.listLanguages();
    if (languages.indexOf(language) === -1) throw new BoxError(BoxError.BAD_FIELD, 'Language not found');

    await settings.set(settings.LANGUAGE_KEY, language);
}

export default {
    getStatus,

    getTimeZone,
    setTimeZone,

    getLanguage,
    setLanguage,
};
