import { BinaryDataType } from "../type/BinaryDataType.js";
import { buildAccessor } from "./buildAccessor.js";

export class DataViewStructAccessor {
    /**
     * @type {DataView}
     */
    $data;

    /**
     * @type {number}
     */
    $offset = 0;

    /**
     * @readonly
     * @type {number}
     */
    $record_byte_size = 0;

    /**
     *
     * @param {Object<BinaryDataType>} schema
     * @param {boolean} [little_endian]
     */
    constructor(schema, little_endian = false) {

        this.$record_byte_size = buildAccessor({
            schema,
            target: this,
            data_variable_name: "this.$data",
            offset_variable_name: "this.$offset",
            little_endian
        });

    }

    /**
     * Mainly here for TS interface's type inference
     * @return {DataViewStructAccessor}
     */
    get record() {
        return this;
    }

    /**
     *
     * @param {DataView} data_view
     * @param {number} byte_offset
     */
    bind(data_view, byte_offset) {
        this.$data = data_view;
        this.$offset = byte_offset;
    }

    /**
     *
     * @param {DataView} data_view
     * @param {number} index
     */
    bind_by_index(data_view, index) {
        this.$data = data_view;
        this.$offset = index * this.$record_byte_size;
    }
}