import { BaseMatcher } from "../BaseMatcher.js";


const RX = /%([0-9]+)/gi;

export class DescribeAs extends BaseMatcher {
    /**
     * @type {string}
     */
    template
    /**
     * @type {Matcher}
     */
    matcher
    /**
     * @type {Array}
     */
    values

    /**
     *
     * @param {string} template
     * @param {Matcher} matcher
     * @param {Array} values
     */
    constructor(template, matcher, values) {
        super();

        this.template = template;
        this.matcher = matcher;
        this.values = values;
    }

    matches(item, mismatch_description) {
        return this.matcher.matches(item, mismatch_description);
    }

    describeTo(description) {

        let textStart = 0;

        const matches = this.template.matchAll(RX);

        for (let i = 0; i < matches.length; i++) {
            const match = matches[i];

            description.appendText(this.template.substring(textStart, match.index));

            const group_index = parseInt(match.groups[1]);

            description.appendValue(this.values[group_index]);

            textStart = match[0].length;
        }
        if (textStart < this.template.length) {
            description.appendText(this.template.slice(textStart));
        }
    }

    describeMismatch(item, mismatch_description) {
        this.matcher.describeMismatch(item, mismatch_description);
    }
}
