"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultPreferredLanguages = exports.languageCodeURIBase = void 0;
exports.addDefaults = addDefaults;
exports.getPreferredLanguagesFor = getPreferredLanguagesFor;
exports.getPreferredLanguages = getPreferredLanguages;
exports.filterByLanguage = filterByLanguage;
/* Logic to access public data stores
*
* including filtering resut by natural language etc
* See https://solidos.solidcommunity.net/public/2021/01%20Building%20Solid%20Apps%20which%20use%20Public%20Data.html
*/
/* eslint-disable no-console */
const debug = __importStar(require("../../../debug"));
// import * as logic from '../index'
// import { authn } from '../../../authn/index'
const solid_logic_1 = require("solid-logic");
const ns_1 = __importDefault(require("../../../ns"));
exports.languageCodeURIBase = 'https://www.w3.org/ns/iana/language-code/'; /// @@ unsupported on the web (2021)
exports.defaultPreferredLanguages = ['en', 'fr', 'de', 'it', 'ar'];
function addDefaults(array) {
    if (!array)
        array = [];
    return array.concat(exports.defaultPreferredLanguages.filter(code => !array.includes(code)));
}
async function getPreferredLanguagesFor(person) {
    const doc = person.doc();
    await solid_logic_1.store.fetcher?.load(doc);
    const list = solid_logic_1.store.any(person, ns_1.default.schema('knowsLanguage'), null, doc);
    if (!list) {
        // console.log(`User ${person} has not set their languages in their profile.`)
        return exports.defaultPreferredLanguages;
    }
    const languageCodeArray = [];
    list.elements.forEach(item => {
        // console.log('@@ item ' + item)
        const lang = solid_logic_1.store.any(item, ns_1.default.solid('publicId'), null, doc);
        if (!lang) {
            console.warn('getPreferredLanguages: No publiID of language.');
            return;
        }
        if (!lang.value.startsWith(exports.languageCodeURIBase)) {
            console.error(`What should be a language code ${lang.value} does not start with ${exports.languageCodeURIBase}`);
            return;
        }
        const code = lang.value.slice(exports.languageCodeURIBase.length);
        languageCodeArray.push(code);
    });
    if (languageCodeArray.length > 0) {
        console.log(`     User knows languages with codes: "${languageCodeArray.join(',')}"`);
        return addDefaults(languageCodeArray);
    }
    return null;
}
/* Get the preferred langauges for the user
 *
 *  Either from solid preferences or browser preferences or default
 */
async function getPreferredLanguages() {
    // In future:  cache in the login session for speed, but get from profile and private prefs
    // We append the defaults so if someone's first choice is not available they don't get something very obscure
    // See https://github.com/solidos/solidos/issues/42
    const me = await solid_logic_1.authn.currentUser();
    if (me) { // If logged in
        const solidLanguagePrefs = await getPreferredLanguagesFor(me);
        if (solidLanguagePrefs)
            return solidLanguagePrefs;
    }
    if (typeof navigator !== 'undefined') { // use browser settings
        if (navigator.languages) {
            return addDefaults(navigator.languages.map(longForm => longForm.split('-')[0]));
        }
        if (navigator.language) {
            return addDefaults([navigator.language.split('-')[0]]);
        }
    }
    return exports.defaultPreferredLanguages;
}
/* From an array of bindings with a names for each row,
 * remove dupliacte names for the same thing, leaving the user's
 * preferred language version
*/
function filterByLanguage(bindings, languagePrefs) {
    const uris = {};
    bindings.forEach(binding => {
        const uri = binding.subject.value;
        uris[uri] = uris[uri] || [];
        uris[uri].push(binding);
    });
    const languagePrefs2 = languagePrefs || exports.defaultPreferredLanguages;
    languagePrefs2.reverse(); // Preferred last
    const slimmed = [];
    // console.log(` @@ {languagePrefs2 ${languagePrefs2}`)
    for (const u in uris) { // needs hasOwnProperty ?
        const bindings = uris[u];
        const sortMe = bindings.map(binding => {
            const lang = binding.name['xml:lang'];
            const index = languagePrefs2.indexOf(lang);
            const pair = [index, binding];
            // console.log(`   @@ lang: ${lang}, index: ${index}`)
            return pair;
        });
        sortMe.sort(); // best at th ebottom
        sortMe.reverse(); // best at the top
        // console.debug('@@ sortMe:', sortMe)
        slimmed.push(sortMe[0][1]);
    } // map u
    debug.log(` Filter by language: ${bindings.length} -> ${slimmed.length}`);
    return slimmed;
}
//# sourceMappingURL=language.js.map