import RuleService from "./RuleService";
import BackgroundService from "./BackgroundService"


export default class EventListener {
    private _ruleService: RuleService;
    private _handledEvents: string[];
    private _newActionCallbacks: Function[];
    private _backgroundService: BackgroundService;

    constructor(ruleService: RuleService, backgroundService: BackgroundService) {
        this._ruleService = ruleService
        this._handledEvents = [];
        this._newActionCallbacks = [];
        this._backgroundService = backgroundService;
    }

    explorationStarted(): void{
        this.listen();
    }

    explorationStopped(): void {
        this.unlisten();
    }

    reload(): void {
        this.unlisten();
        this.listen();
    }

    private listen() {
        const events = this._ruleService.getEventsToHandle()
        this._handledEvents = events;
        this._handledEvents.forEach((handledEvent) => {
            window.addEventListener(handledEvent, this.exploratoryListener.bind(this), true)
        });
    }

    private unlisten() {
        this._handledEvents.forEach((handledEvent) => {
            window.removeEventListener(handledEvent, this.exploratoryListener.bind(this), true)
        });
    }

    private exploratoryListener(event): Promise<void> {
        //console.log('listen:',event);
        if (!event.explored) {
            event.explored = true;
            let rule = this._ruleService.getMatchingRule(event);
            if (rule) {
                const action = rule.makeAction(event);
                if (action) {
                    //console.log('action:',action)
                    return this._backgroundService.sendAction(action).then(() => {
                        //this._newActionCallbacks.forEach(callback => callback(action));
                    })
                } else {
                    return Promise.resolve()
                }
            } else {
                return Promise.resolve()
            }
        } else {
            return Promise.resolve()
        }
    }

    public addActionPushedToBackgroundListener(callback) {
        if (typeof callback === "function") {
            this._newActionCallbacks.push(callback)
        }
    }
}
