const Vue = require('vue');
const db = require('../database');
const config = require('../config');
const fallbackLocale = config.i18n.fallbackLocale;
const userLocale = {
    async serverPrefetch() {
        if (this.auth)
            this.$i18n.locale = this.auth.locale;

        if (this.recipientId)
            this.$i18n.locale = await this.getLocale(this.recipientId);
    },
    methods: {
        getLocale(recipientId) {
            return db.findOne(`
                SELECT IF(u.lang IS NOT NULL, u.lang, LOWER(ct.code)) lang 
                    FROM client c
                        JOIN country ct ON ct.id = c.countryFk
                        JOIN account.user u ON u.id = c.id
                WHERE c.id = ?`, [recipientId]).then(rows => {
                if (rows)
                    return rows.lang;
                else return fallbackLocale;
            });
        }
    },
    props: ['recipientId']
};

Vue.mixin(userLocale);