"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CaretValue = void 0;
const tslib_1 = require("tslib");
const bin_util_1 = require("@ot-builder/bin-util");
const ImpLib = tslib_1.__importStar(require("@ot-builder/common-impl"));
const errors_1 = require("@ot-builder/errors");
const variance_1 = require("@ot-builder/variance");
const device_table_1 = require("../shared/device-table");
exports.CaretValue = {
    ...(0, bin_util_1.Read)((view, ivs) => {
        const format = view.lift(0).uint16();
        switch (format) {
            case 1:
                return view.next(CaretValueFormat1);
            case 2:
                return view.next(CaretValueFormat2);
            case 3:
                return view.next(CaretValueFormat3, ivs);
            default:
                throw errors_1.Errors.FormatNotSupported("ligCaretValue", format);
        }
    }),
    ...(0, bin_util_1.Write)((frag, caret, ivs) => {
        if (caret.pointAttachment)
            return frag.push(CaretValueFormat2, caret);
        else
            return frag.push(CaretValueFormat3, caret, ivs);
    })
};
const CaretValueFormat1 = {
    ...(0, bin_util_1.Read)(view => {
        const format = view.uint16();
        if (format !== 1)
            throw errors_1.Errors.Unreachable();
        return { x: view.uint16() };
    }),
    ...(0, bin_util_1.Write)((frag, caret) => {
        frag.uint16(1).int16(ImpLib.Arith.Round.Coord(variance_1.OtVar.Ops.originOf(caret.x)));
    })
};
const CaretValueFormat2 = {
    ...(0, bin_util_1.Read)(view => {
        const format = view.uint16();
        if (format !== 2)
            throw errors_1.Errors.Unreachable();
        return { x: 0, pointAttachment: { pointIndex: view.uint16() } };
    }),
    ...(0, bin_util_1.Write)((frag, caret) => {
        if (!caret.pointAttachment)
            throw errors_1.Errors.Unreachable();
        frag.uint16(2).int16(variance_1.OtVar.Ops.originOf(caret.pointAttachment.pointIndex));
    })
};
const CaretValueFormat3 = {
    ...(0, bin_util_1.Read)((view, ivs) => {
        const format = view.uint16();
        if (format !== 3)
            throw errors_1.Errors.Unreachable();
        let x = view.int16();
        const dd = view.next(device_table_1.Ptr16DeviceTable, ivs);
        x = variance_1.OtVar.Ops.add(x, dd ? dd.variation : 0);
        return { x: x, xDevice: dd ? dd.deviceDeltas : undefined };
    }),
    ...(0, bin_util_1.Write)((frag, caret, ivs) => {
        if (variance_1.OtVar.Ops.isConstant(caret.x) && !caret.xDevice) {
            frag.push(CaretValueFormat1, caret);
        }
        else {
            frag.uint16(3)
                .int16(ImpLib.Arith.Round.Coord(variance_1.OtVar.Ops.originOf(caret.x)))
                .push(device_table_1.Ptr16DeviceTable, { deviceDeltas: caret.xDevice, variation: caret.x }, ivs);
        }
    })
};
//# sourceMappingURL=lig-caret-value.js.map