import { querySelectorAllDeep } from 'query-selector-shadow-dom';
import ActionStrategy from './ActionStrategy';
import Action from '../../Action';
import Rule from '../Rule';


export default class InnerTextStrategy implements ActionStrategy {

    static makeAction(rule: any, event: any, listenedElement: any): Action {
        return new Action(rule.prefix, listenedElement.innerText);
    }
    
    static actionToElements(rule: Rule, action: Action): Element[] {
        if (action.prefix !== rule.prefix) {
            return [];
        }
        let elements;
        if (rule.xpath){
            let result = document.evaluate(rule.xpath, document, null, XPathResult.ANY_TYPE, null);
            elements = [];
            let node = result.iterateNext();
            while (node) {
                elements.push(node);
                node = result.iterateNext();
            }            
        } else {
            elements = querySelectorAllDeep(rule.css);
        }
        if (action.suffix) {
            return elements.filter(domElement => 
                domElement.innerText.trim() === action.suffix.trim()
            )
        //Happens if a previous rules was not using the innerText suffix
        } else {
            return elements;
        }
    }
}