import React, {Component, PropTypes} from 'react';

export default class CopyToClipboard extends Component {

    constructor(props, context) {
        super(props, context);
        this.state = {
            success: false
        };
    }

    static propType = {
        copyText: PropTypes.string
    };

    handleClick() {
        const targetId = '_hiddenCopyText_';
        let target = document.getElementById(targetId);
        if (!target) {
            target = document.createElement("textarea");
            target.style.position = "absolute";
            target.style.left = "-9999px";
            target.style.top = "0";
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = this.props.copyText || '';

        // select the content
        let currentFocus = document.activeElement;
        target.focus();
        target.setSelectionRange(0, target.value.length);

        // copy the selection
        let success;
        try {
            success = document.execCommand("copy");
        } catch (e) {
            success = false;
        }
        // restore original focus
        if (currentFocus && typeof currentFocus.focus === "function") {
            currentFocus.focus();
        }

        // clear temporary content
        target.textContent = "";

        if (success) {
            
            this.setState({success});

            setTimeout(()=> {
                this.setState({success: false});
            }, 1500);
        }
    }

    render() {
        const styles = require('./CopyToClipboard.less');
        return (
            <div className={styles.copybox} onClick={this.handleClick.bind(this)}>
                {this.props.children}
                {
                    this.state.success &&
                        <div className={styles.success}>
                            Copied!
                        </div>
                }
            </div>
        );
    }
}
