import Interface4TabScript from "../application/Interface4TabScript";

export default class HandlerOfMessageSentByTabScript {
    private _application : Interface4TabScript;

    constructor(application: Interface4TabScript) {
        this._application = application;
        chrome.runtime.onMessage.addListener(this.handleMessage.bind(this));
    }

    private handleMessage(msg, sender, sendResponse): boolean {
        switch (msg.kind) {

			case "getStateForTabScript": {
				sendResponse(this._application.getStateForTabScript());
				return true;
            }

            case "getProbabilities": {
                this._application.getProbabilities()
                    .then((response) => {
                        if (!response) {
                            sendResponse();
                            return true;
                        }
                        sendResponse({
                            state: response.state,
                            probabilityMap: JSON.parse(response.probabilityMap)
                        });
                    })
                    .catch((error) => {
                        console.log('error:',error);
                        sendResponse();
                    });
                return true;
            }

            case "getExplorationEvaluation": {
                const evaluation = this._application.getExplorationEvaluation()
                sendResponse(evaluation);
                return true;
            }

            case "getComments": {
                this._application.getComments()
                    .then((response) => {
                        if (!response) {
                            sendResponse();
                            return true;
                        }
                        sendResponse({
                            state: response.state,
                            commentDistributionList: JSON.parse(response.commentDistributionList)
                        });
                    })
                    .catch((error) => {
                        console.log(error);
                        sendResponse();
                    });
                    return true;
            }

            case "pushAction": {
                const action = msg.action;
                this._application.addActionToExploration(action.prefix, action.suffix).then(() => {
                    sendResponse("ok");
                });
                return true;
            }

            case "upComment": {
                this._application.upComment(msg.type, msg.value);
                sendResponse("ok");
                return true;
            }

            case "setPopupCommentPosition": {
                this._application.setPopupCommentPosition(msg.popupCommentPosition);
                sendResponse("ok");
                return true;
            }

        }
    }
}