import * as React from 'react';
import PropTypes from 'prop-types';
import {CopyToClipboard} from 'react-copy-to-clipboard';
import * as Prism from 'prismjs';
import './style.scss';
import Icon from '../Icon';
import Translate from "../Translate";

export default class CodeViewer extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            copied: false,
        };
    }

    componentDidMount() {
        this.highlight();
    }

    componentDidUpdate() {
        this.highlight();
    }

    highlight() {
        Prism.highlightElement(this.wrapperNode);
    }

    mountRef = (node) => {
        this.wrapperNode = node;
    }

    copiedHandler = () => {
        this.setState({copied: true});
        window.setTimeout(() => {
            this.setState({copied: false});
        }, 3000);
    }

    render() {
        let copyToClipboard;
        if (this.props.copyingEnabled) {
            if (this.state.copied) {
                copyToClipboard = (
                    <p className="CodeViewer__copy-block">
                        <Icon
                            name="check"
                            size="small"
                            color="green"
                            classNames="CodeViewer__copy-icon"
                        />
                        <Translate tag="copied" />
                    </p>
                );
            } else {
                copyToClipboard = (
                    <CopyToClipboard
                        onCopy={() => this.copiedHandler()}
                        text={this.props.children}
                    >
                        <button className="button button_primary">
                            <Translate tag="copy_code" />
                        </button>
                    </CopyToClipboard>
                );
            }
            copyToClipboard = (
                this.props.children &&
                <div className="CodeViewer__copy">
                    {copyToClipboard}
                </div>
            );
        }

        return (
            <div className="CodeViewer">
                <pre>
                    <code
                        className={`lang-${this.props.language}`}
                        ref={this.mountRef}
                    >
                        {this.props.children}
                    </code>
                </pre>
                {copyToClipboard}
            </div>
        );
    }
}

CodeViewer.propTypes = {
    children: PropTypes.any,
    language: PropTypes.string,
    copyingEnabled: PropTypes.bool,
};

CodeViewer.defaultProps = {
    children: null,
    language: 'markup',
    copyingEnabled: true,
};
