import Action from './Action';
import SimpleRule from './SimpleRule';

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

    makeAction(event): Action | null{
        const 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 [];
        }
        if(action.suffix === undefined) {
            return super.actionToElements(action);
        }
        const index = parseInt(action.suffix, 10);
        const 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;
        }
    }
}
