import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as Styled from './toast.style';

export default class Toast extends React.Component<Props, State> {
    _handle: number;
    state = {
        text: "",
        isShow: false
    };

    public toast({text, delay = 2000}: {text: string, delay: number}) {
        if (this._handle) {
            window.clearTimeout(this._handle)
            this._handle = null;
        }
        this.setState({
            text,
            isShow: true
        });

        this._handle = window.setTimeout(() => {
            this.setState({
                isShow: false
            })
            this._handle = null;
        }, delay);
    }

    public render() {
        return (
            <Styled.Toast className="m-toast aBouncein" style={{"display": this.state.isShow? "block" : "none"}}>
                <div className="inner">
                    <div className="main">{this.state.text}</div>
                </div>
            </Styled.Toast>
        );
    }
}

var toastIns = null;
var defaults = {
    delay: 2000,
    parent: document.body
};

export function config(options) {
    defaults = Object.assign({}, defaults, options);
};

export function showMessage(options) {
    if (typeof options === 'string') {
        options = {text: options}
    }
    options = Object.assign({}, defaults, options);

    if (!toastIns) {
        var div = document.createElement('div');
        options.parent.appendChild(div);

        toastIns = ReactDOM.render(
            <Toast />,
            div
        );
    }

    toastIns.toast({
        text: options.text,
        delay: options.delay
    });
};
