import Action from './Action';
import Rule from './Rule';
import getCssSelector from 'css-selector-generator';

export default class CSSSelectorRule extends Rule {
    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 {
        // console.log('makeAction with prefix = ', this.prefix);
        if (event.target) {
            // console.log(event.target);
            let suffix;
            try {
                suffix = getCssSelector(event.target, {selectors: ['id', 'class', 'tag']});
            } catch (e) {
                console.log("exception:",e);
            }
            return new Action(this.prefix, suffix);
        }
        return new Action(this.prefix);
    }

    actionToElements(action: Action): Element[] {
        if (action.prefix !== this.prefix) {
            return [];
        }

        if (action.suffix) {
            const elements : Element[] = [];
            const parentElements = this.findMatchedElements();
            document.querySelectorAll(action.suffix).forEach( (element) => {
                if (parentElements.some((parent) => parent.contains(element))) {
                    elements.push(element);
                }
            });
            return elements;
        } else {
            return [];
        }
    }
}
