import * as puppeteer from "puppeteer";
import config from "../../config";
import Word from "../word";
import Action from "./action";

export default class ActionPipeline {

    public actions: Action[];

    constructor() {
        this.actions = [];
    }

    public addAction(action: Action): void {
        this.actions.push(action);
    }

    public execute(): Promise<Action[]> {
        let browser;
        const executedWords = [];
        return new Promise((resolve) => {
            puppeteer.launch({
                timeout: config.TIMEOUT,
                headless: config.HEADLESS,
            })
                .then((newBrowser) => {
                    browser = newBrowser;
                    return browser.newPage();
                })
                .then(async (page) => {
                    for (const action of this.actions) {
                        try {
                            await action.execute(page);
                            executedWords.push(action);
                        } catch (e) {
                            console.log("skip ", action.word);
                        }
                    }
                })
                .then(() => browser.close())
                .then(() => resolve(executedWords))
                .catch((e) => {
                    console.log(e);
                    resolve(executedWords);
                });
        });

    }

}
