import Interface4Popup from "../application/Interface4Popup";
import ExtensionCommunicationService from "./ExtensionCommunicationService";
import {logger} from "../framework/Logger";

export default class HandlerOfMessageSentByPopup {
    private _application : Interface4Popup;

    constructor(application: Interface4Popup) {
        this._application = application;
    }

    public attachCommunicationService(extensionCommunicationService : ExtensionCommunicationService): void {
        extensionCommunicationService.addOnMessageListener(this.handleMessage.bind(this));
    }

    private handleMessage(msg : any, sender : any, sendResponse : Function): boolean {
        logger.info(`Popup asks for ${msg.kind}`);
        switch (msg.kind) {
            case "checkDeprecated": {
				this._application.makeCompatibilityCheck()
					.then((compatibilityCheck) => {
                        logger.debug(`compatibilityCheck: ${compatibilityCheck}`);
						sendResponse(compatibilityCheck);
					})
					.catch((error) => {
						logger.error("popup asks for checkDeprecated",error);
						sendResponse(error);
					});
				return true;
			}

			case "getStateForPopup": {
                let state = this._application.getStateForPopup();
                logger.debug(`state is returned`);
				sendResponse(state);
				return true;
			}

            case "connect": {
                if (!msg.connectionCode) {
                    logger.debug(`connection refused`);
                    sendResponse("nok");
                    return true;
                }
                if (!msg.connectionCode.includes('$')) {
                    logger.debug(`connection refused`);
                    sendResponse("nok");
                    return true;
                }
                const [sessionId, modelId] = msg.connectionCode.split("$");
                this._application
                    .connect(sessionId, modelId)
                    .then(() => {
                        logger.debug(`connection accepted`);
                        sendResponse("ok");
                    })
                    .catch((error) => {
                        logger.error("popup asks to connect", error)
                        sendResponse("nok")
                    });
                return true;
            }

            case "disconnect": {
                this._application
                    .disconnect()
                    .then(() => {
                        sendResponse("ok");
                    })
                    .catch((error) => {
                        sendResponse({ error });
                        logger.error("popup asks to disconnect",error);
                    });
                return true;
            }

            case "reloadWebSite": {
                this._application
                    .reloadWebsite()
                    .then(() => {
                        sendResponse("ok");
                    })
                    .catch((error) => {
                        logger.error("popup asks to reloadWebSite",error);
                        sendResponse(error);
                    });
                return true;
            }

            case "startExploration": {
                this._application
                    .startExploration()
                    .then(() => {
                        logger.info(`start exploration`);
                        sendResponse(this._application.getStateForPopup());
                    })
                    .catch((error) => {
                        logger.error("popup asks to startExploration",error);
                        sendResponse({error});
                    });
                return true;
            }

            case "stopExploration": {
                this._application
                    .stopExploration()
                    .then(() => {
                        // logger.info('stopped');
                        sendResponse(this._application.getStateForPopup());
                    })
                    .catch((error) => {
                        logger.error("popup asks to stopExploration",error);
                        sendResponse(error);
                    });
                return true;
            }

            case "removeExploration": {
                this._application
                    .removeExploration()
                    .then(() => {
                        sendResponse(this._application.getStateForPopup());
                    }).catch((error) => {
                        logger.error("popup asks to removeExploration",error);
                        sendResponse(error);
                    });
                return true;
            }

            case "changeTesterName": {
				this._application.changeTesterName(msg.testerName);
                sendResponse(this._application.getStateForPopup());
				return true;
            }

            case "setCreateNewWindowOnConnect": {
                this._application.setShouldCreateNewWindowsOnConnect(msg.shouldCreateNewWindowOnConnect);
                sendResponse(this._application.getStateForPopup());
                return true;
            }

            case "setCloseWindowOnConnect": {
                this._application.setShouldCloseWindowOnDisconnect(msg.shouldCloseWindowOnDisconnect);
                sendResponse(this._application.getStateForPopup());
                return true;
            }

            case "setIsTabScriptDiplayingUserView": {
				this._application.setIsTabScriptDisplayingUserView(msg.isTabScriptDisplayingUserView);
                sendResponse(this._application.getStateForPopup());
				return true;
            }

            case "restartExploration": {
                this._application
                .restartExploration()
                .then(() => {
                    sendResponse(this._application.getStateForPopup());
                })
                .catch((error) => {
                    logger.error("popup asks to restartExploration",error);
                    sendResponse(error);
                });
                return true;
            }

            case "pushComment": {
                const { type, value } = msg;
                this._application.addCommentToExploration(type, value);
                sendResponse("ok");
                return true;
            }

            case "takeScreenshot": {
                this._application.takeScreenShot();
                sendResponse("ok");
                return true;
            }

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

            case "setRecordMediaStatus" : {
                this._application.setRecordMedia(msg.recordMediaStatus)
                .then(() => {
                    sendResponse("ok");
                })
                .catch( (e) => {
                    logger.error("popup asks to setRecordMediaStatus", e);
                    sendResponse("notok");
                })
                return true;
            }

            case "toggleDetachPopup": {
                this._application.toggleDetachPopup()
                .then(() => {
                    sendResponse("ok");
                })
                .catch((error) => {
                    logger.error("popup asks to toggleDetachPopup",error)
                    sendResponse({error});
                })
                return true;
            }

            default : {
                logger.debug(`${msg.kind} is not considered to come from popup`);
                return true;
            }

        }
    }



}