import AbstractAdminareaCommunicationService from '../../Framework/Services/AbstractAdminareaCommunicationService';
import get from 'lodash/get';
import { getConf } from '../configuration';
import { Services } from '../ServiceLocator';
import createMessageInterface from '../Utils/createMessageInterface';

/**
 * Service that handles the postMessage Communication with the admin area
 *
 * The configurator is included into the adminarea as an IFrame at some areas
 */
export default class AdminareaCommunicationService extends AbstractAdminareaCommunicationService {
    init() {
        const adminMode = getConf('adminMode');
        if (adminMode) {
            const messageInterface = createMessageInterface();
            messageInterface.addListener('getConfiguration', async event => {
                const configuration = await Services.interaction.adminGetConfiguration();
                event.source.postMessage({ ...event.data, adminMode, configuration }, event.origin);
            });
        }
    }

    /**
     * Saves a configuration (e.g. for inspirations or default configuration)
     *
     * @param {object} configuration
     * @param {string} configurationtype
     */
    saveConfiguration(configuration, configurationtype) {
        const payload = {
            configuration: configuration,
            configurationtype: configurationtype,
        };

        return new Promise(resolve => {
            this.sendPostMessage('saveConfiguration', payload);
            resolve();
        });
    }

    sendPostMessage(method, payload) {
        if (window.parent !== undefined && window.parent.postMessage !== undefined) {
            const appConf = getConf();
            const targetOrigin = get(appConf, 'adminareaPostMessageTargetOrigin', '*');

            const messagePayload = {
                method: method,
                ...payload,
            };

            window.parent.postMessage(messagePayload, targetOrigin);

            // eslint-disable-next-line no-console
            console.info(
                '[AdminareaCommunicationService] the following message has been posted:',
                messagePayload
            );
        }
    }
}
