import React from 'react';
import loadjs from 'loadjs';
import { getConf } from 'App/configuration';
import PropTypes from 'prop-types';

/**
 * @deprecated Used only in legacy projects
 */
export default class ExternalVisualization extends React.Component {
    static propTypes = {
        configuration: PropTypes.object,
    };

    constructor(props) {
        super(props);
        this.loadjs = loadjs;
        // eslint-disable-next-line no-console
        console.warn(
            'ExternalVisualization should only be used as a backward compatibility wrapper for older projects.'
        );
    }

    componentDidMount() {
        this.loadVisualizationComponent();
    }

    componentDidUpdate(prevProps) {
        // update Visualization component if it is present
        if (this.visualizationcomponent !== undefined && this.shouldUpdateVisualizationComponent(prevProps)) {
            this.visualizationcomponent.update(this.props.configuration);
        }
    }

    getVisualizationResourcesURL() {
        return getConf('network.resourcesURL', '/');
    }

    getVisualizationCustomConfiguration() {
        return {};
    }

    loadVisualizationComponent() {
        let self = this;

        // load the visualization component's javascript asynchronously and init it
        this.loadjs(['/visualizationcomponent/visualizationcomponent.js'], 'visualizationcomponent');
        this.loadjs.ready('visualizationcomponent', {
            success: function() {
                let config = {
                    basePath: self.getVisualizationResourcesURL(),
                };

                let customConfig = self.getVisualizationCustomConfiguration();
                config = Object.assign(config, customConfig);

                // eslint-disable-next-line no-undef
                self.visualizationcomponent = new Visualizationcomponent();
                self.visualizationcomponent.init(
                    config,
                    function() {},
                    function() {},
                    self.loadjs
                );
            },
            error: function() {},
        });
    }

    /**
     * Override this function to fine tune the visualization component updates
     * @param {object} prevProps
     * @returns {boolean}
     */
    // eslint-disable-next-line no-unused-vars
    shouldUpdateVisualizationComponent(prevProps) {
        return true;
    }

    setRef = ref => (this.container = ref);

    render() {
        return (
            <div
                id="visualizationcomponentcontainer"
                className="visualizationcomponentcontainer"
                ref={this.setRef}
            />
        );
    }
}
