import React from 'react';

import CreateUserForm from 'components/User/Forms/Create';
import isAllowedIframeOrigin from 'lib2/isAllowedIframeOrigin';

import './index.css';

export class CreateUserWidget extends React.PureComponent {
    constructor(props) {
        super(props);

        const query = new URLSearchParams(window.location.search);

        this.state = {
            departmentId: parseInt(query.get('departmentId'), 10) || undefined,
            source: query.get('source'),
        };

        this._initRef = this._initRef.bind(this);
        this._onMessage = this._onMessage.bind(this);
        this._updateSize = this._updateSize.bind(this);
        this._postMessage = this._postMessage.bind(this);
        this._onSubmit = this._onSubmit.bind(this);
        this._onCancel = this._onCancel.bind(this);
    }

    componentDidMount() {
        document.body.className = 'loaded connect-app connect-widget';
        window.addEventListener('message', this._onMessage);
        window.parent.postMessage('ping', '*');
    }

    componentWillUnmount() {
        this._unmounted = true;
        clearInterval(this._resizeTracker);
        window.removeEventListener('message', this._onMessage);
    }

    render() {
        const { departmentId, source } = this.state;

        return (
            <div className="create-user-widget" ref={this._initRef}>
                <CreateUserForm
                    source={source}
                    redirect={false}
                    departmentId={departmentId}
                    onSubmit={this._onSubmit}
                    onCancel={this._onCancel}
                />
            </div>
        );
    }

    _initRef(ref) {
        this._ref = ref;
    }

    /**
     * @param {MessageEvent} param
     */
    _onMessage({ data, origin }) {
        if (data === 'pong' && isAllowedIframeOrigin(origin)) {
            this._targetOrigin = origin;
            this._updateSize(true);

            clearInterval(this._resizeTracker);
            this._resizeTracker = setInterval(this._updateSize, 300);
        }
    }

    /**
     * @param {Boolean} force
     */
    _updateSize(force) {
        const { offsetWidth, offsetHeight } = this._ref;

        if (force || this._width !== offsetWidth || this._height !== offsetHeight) {
            this._postMessage('resize', {
                width: offsetWidth,
                height: offsetHeight,
            });

            this._width = offsetWidth;
            this._height = offsetHeight;
        }
    }

    /**
     * @param {String} type
     * @param {Object} payload
     */
    _postMessage(type, payload) {
        type = `@connect/create-user/${type}`;

        this._targetOrigin && window.parent.postMessage({ type, payload }, this._targetOrigin);
    }

    _onCancel() {
        this._postMessage('cancel');
    }

    _onSubmit(data) {
        if (data && data.users) {
            const [userData] = Object.values(data.users);

            if (userData) {
                this._postMessage('submit', userData);
            }
        }
    }
}
