import PropTypes from 'prop-types';
import React from 'react';
import Loader from 'ui-components/lib/Loader';

// документация по встраиванию форм:
// https://github.yandex-team.ru/pages/yandex-events/yandex-tech-api-docs/docs.html#vstraivanie-formyi-v-iframe

const FeedbackForm = React.createClass({

    getInitialState() {
        return { isLoading: true };
    },

    componentWillUnmount() {
        if (this._postMessageListener) {
            window.removeEventListener('message', this._postMessageListener);
        }
    },

    _afterLoading() {
        this.setState({ isLoading: false });
    },

    _initialize(element) {
        this._postMessageListener = event => {
            let { data } = event;
            const { source } = event;

            try {
                data = JSON.parse(data);
            } catch (e) {
                // empty
            }

            if (!data) {
                return;
            }

            if (data === 'ping' || data.message === 'ping') {
                source.postMessage('pong', '*');
            }

            if (element && data['iframe-height']) {
                element.style.height = `${data['iframe-height']}px`;
            }

            const { onSend, onMessage } = this.props;

            if (onMessage && data.message) {
                onMessage(data);
            }

            if (onSend && data.message === 'sent') {
                onSend();
            }
        };

        window.addEventListener('message', this._postMessageListener);
    },

    render() {
        const { className, name } = this.props;
        const { isLoading } = this.state;
        let { src } = this.props;

        if (/\/\/forms\.yandex(\-team)?\./.test(src) && !/[\?&]iframe=1/.test(src)) {
            src += `${src.indexOf('?') === -1 ? '?' : '&'}iframe=1`;
        }

        return (
            <div>
                <Loader visible={isLoading} />
                <iframe
                    ref={this._initialize}
                    className={className}
                    frameBorder="0"
                    name={name}
                    src={src}
                    onLoad={this._afterLoading}
                />
            </div>
        );
    },

});

// @if NODE_ENV='development'
FeedbackForm.propTypes = {
    src: PropTypes.string,
    className: PropTypes.string,
    name: PropTypes.string,
    onSend: PropTypes.func,
};
// @endif

FeedbackForm.defaultProps = {
    className: 'feedback-form',
    name: 'feedback-form',
};

export default FeedbackForm;
