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": {
                console.log('getProbabilities');
                this._application.getProbabilities()
                    .then((response) => {
                        if (!response) {
                            console.log('getProbabilities : no answer');
                            sendResponse();
                            return true;
                        }
                        console.log('getProbabilities : answer');
                        sendResponse({
                            state: response.state,
                            probabilityMap: Array.from(response.probabilityMap),
                            followedProbabilityMap: response.followedProbabilityMap ? Array.from(response.followedProbabilityMap): undefined,
                        });
                    })
                    .catch((error) => {
                        console.log('error:',error);
                        sendResponse();
                    });
                return true;
            }

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

            case "pushAction": {
                const action = msg.action;
                this._application.addActionToExploration(action.prefix, action.suffix);
                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;

            }
        }
    }
    


}