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

export default class IndexStrategy implements ActionStrategy {
    static makeAction(rule, event, listenedElement): Action {
        let matchingElements;
        if (rule.xpath) {
            let result = document.evaluate(rule.xpath, document, null, XPathResult.ANY_TYPE, null);
            matchingElements = [];
            let node = result.iterateNext();
            while (node) {
                matchingElements.push(node);
                node = result.iterateNext();
            }
        } else {
            matchingElements = querySelectorAllDeep(rule.css)
        }
        
        for (let i = 0; i < matchingElements.length; i++) {
            if (matchingElements[i] === listenedElement) {
                return new Action(rule.prefix, i.toString());
            }
        }
        return null
    }
    
    static actionToElements(rule: Rule, action: Action): Element[] {
        if (action.prefix !== rule.prefix) {
            return [];
        }
        const index = action.suffix;
        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);
        }
    
        //Happens if a previous rules was not using the index suffix
        if (index) {
            if (elements.length > index) {
                return [elements[index]];
            } else {
                return [];
            }
        } else {
            return elements
        }
    }
}
