import { DataManager } from './pwa-core.js';
import { AbstractSite, FlashMessenger, Helper, InitPromise, Translator } from './pwa-lib.js';

class Code {
    constructor(args) {
        if (typeof args === "string") {
            args = {
                "code": args
            };
        }
        this.args = args;
        this.isCacheable = false;
    }

    setIsCacheable(isCacheable) {
        this.isCacheable = isCacheable;
    }

    getIsCacheable() {
        return this.isCacheable;
    }

    activate() {
        return DataManager.send("c/code", this.args);
    }
}

class CodeSite extends AbstractSite {
    constructor(siteManager) {
        super(siteManager, "core/html/load.html", "code");
    }

    onConstruct(args) {
        super.onConstruct(args);
        console.log(args);

        let resPromise = Promise.resolve();
        if (Helper.isNotNull(args["code"])) {
            let code = args["code"];
            let isCachable = Helper.nonNull(args["cachable"], false);

            let codeObject = new Code(code);
            codeObject.setIsCacheable(isCachable);

            let self = this;
            resPromise = codeObject.activate().then(function (res) {
                if (!res["success"]) {
                    FlashMessenger.addMessage(FlashMessenger.MESSAGE_TYPE_SUCCESS, Translator.translate(res["errors"][0]));
                }
                else {
                    FlashMessenger.addMessage(FlashMessenger.MESSAGE_TYPE_SUCCESS, Translator.translate(Helper.nonNull(res["result"]["successMessage"], "code-activated")));
                }
                self.finish();
            });
        }
    }
}

InitPromise.addPromise(function (app) {
    app.addDeepLink("code", CodeSite);
});

export { Code, CodeSite };
