import { string_capitalize } from "../../primitives/strings/string_capitalize.js";
import { read_property } from "./read_property.js";

/**
 * @template T
 * @param {Object} root
 * @param {string[]} parts
 * @param {number} part_offset
 * @param {number} part_count
 * @param {T} value
 */
export function write_property(root, parts, part_offset, part_count, value) {

    const last_index = part_offset + part_count - 1;

    // resolve parent of the property
    const thing = read_property(root, parts, 0, last_index, true);

    const last_part = parts[last_index];

    const setter_name = `set${string_capitalize(last_part)}`;
    const setter = thing[setter_name];

    if (typeof setter === "function") {
        // resolve via setter
        setter.call(thing, value);
    } else {
        // write directly to the field
        thing[last_part] = value;
    }
}

