import Action from './Action';
import Rule from './Rule';

export default class IndexRule extends Rule {
    constructor(prefix, suffix, event, css, xpath, code, key, contextURL, contextCSS, contextXPath) {
        super(prefix, suffix, event, css, xpath, code, key, contextURL, contextCSS, contextXPath);
    }

    makeAction(event): Action | null{
        let matchingElements = this.findMatchedElements();
        for (let i = 0; i < matchingElements.length; i++) {
            if (matchingElements[i].contains(event.composedPath()[0])) {
                return new Action(this.prefix, i.toString());
            }
        }
        return null;
    }
    
    actionToElements(action: Action): Element[] {
        if (action.prefix !== this.prefix) {
            return [];
        }
        const index = parseInt(action.suffix);
        let elements = this.findMatchedElements();
        //Happens if a previous rules was not using the index suffix
        if (index !== undefined || null) {
            if (elements.length > index) {
                return [elements[index]];
            } else {
                return [];
            }
        } else {
            return elements;
        }
    }
}
