import StyleApplication from "../application/StyleApplication";
import EventListenerApplication from "../application/EventListenerApplication";
import BackgroundMessageListener from "../application/BackgroundMessageListener";

export default class ChromeMessageListener implements BackgroundMessageListener {

    styleApplication: StyleApplication;
    eventListener: EventListenerApplication;

    constructor(styleApplication: StyleApplication, eventListener: EventListenerApplication) {
        this.styleApplication = styleApplication;
        this.eventListener = eventListener;
    }

    listenBackground() {
        chrome.runtime.onMessage.addListener(

            (msg, sender, sendResponse) => {
                const error = chrome.runtime.lastError;
                if (error) {
                    console.error(error);
                }

                switch (msg.kind) {
                    case "explorationStarted": 
                        this.styleApplication.onExplorationStarted();
                        this.eventListener.onExplorationStarted();
                        sendResponse("ok");
                        break;

                    case "explorationStopped":
                        this.styleApplication.onExplorationStopped();
                        this.eventListener.onExplorationStopped();
                        sendResponse("ok");
                        break;

                    case "reload":
                        this.styleApplication.onReload();
                        this.eventListener.onReload();
                        //console.log("reload");
                        sendResponse("ok");
                        break;

                    case "checkRunning":
                        sendResponse("ok");
                        break;

                    default:
                        console.log("unhandled message ", msg);
                        sendResponse("ok")
                    }
            });
    }
}