"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CScriptList = void 0;
const bin_composite_types_1 = require("@ot-builder/bin-composite-types");
const primitive_1 = require("@ot-builder/primitive");
class CLangSysTable {
    read(view, fOrd) {
        const vLookupOrder = view.ptr16Nullable(); // Reserved, keep zero
        const requiredFeature = fOrd.tryAt(view.uint16()); // 0xFFFF should return undefined
        const featureIndexCount = view.uint16();
        const features = view.array(featureIndexCount, primitive_1.UInt16).map(id => fOrd.at(id));
        return { requiredFeature, features };
    }
    write(frag, lang, fOrd) {
        frag.uint16(0);
        frag.uint16(fOrd.tryReverseFallback(lang.requiredFeature, 0xffff));
        frag.uint16(lang.features.length);
        frag.array(primitive_1.UInt16, lang.features.map(f => fOrd.reverse(f)));
    }
}
function CPtr16LangSysTable() {
    return (0, bin_composite_types_1.NullablePtr16)(new CLangSysTable());
}
class CScriptTable {
    read(view, fOrd) {
        const defaultLangSys = view.next(CPtr16LangSysTable(), fOrd);
        const langSysCount = view.uint16();
        const script = { defaultLanguage: defaultLangSys, languages: new Map() };
        for (let lid = 0; lid < langSysCount; lid++) {
            const langSysTag = view.next(primitive_1.Tag);
            const lang = view.ptr16().next(new CLangSysTable(), fOrd);
            script.languages.set(langSysTag, lang);
        }
        return script;
    }
    write(frag, script, fOrd) {
        frag.push(CPtr16LangSysTable(), script.defaultLanguage, fOrd);
        const langs = [...script.languages].sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
        frag.uint16(langs.length);
        for (const [tag, lang] of langs) {
            frag.push(primitive_1.Tag, tag);
            frag.ptr16New().push(new CLangSysTable(), lang, fOrd);
        }
    }
}
class CScriptList {
    read(view, fOrd) {
        const scriptCount = view.uint16();
        const scripts = new Map();
        for (let lid = 0; lid < scriptCount; lid++) {
            const tag = view.next(primitive_1.Tag);
            const script = view.ptr16().next(new CScriptTable(), fOrd);
            scripts.set(tag, script);
        }
        return scripts;
    }
    write(frag, scripts, fOrd) {
        const ss = [...scripts].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
        frag.uint16(ss.length);
        for (const [tag, script] of ss) {
            frag.push(primitive_1.Tag, tag);
            frag.ptr16New().push(new CScriptTable(), script, fOrd);
        }
    }
}
exports.CScriptList = CScriptList;
//# sourceMappingURL=script-lang.js.map