import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
	Message as SemanticMessage,
	Transition as SemanticTransition
} from 'semantic-ui-react';

import * as styles from './Style.less';

export default class Toast extends Component {
	static propTypes = {
		content: PropTypes.string.isRequired,
		icon: PropTypes.string,
		type: PropTypes.string,
		duration: PropTypes.number,
		animationDuration: PropTypes.number,
		animation: PropTypes.string
	};

	static defaultProps = {
		icon: null,
		type: 'success',
		duration: 5000,
		animationDuration: 500,
		animation: 'fade down'
	};

	constructor(props) {
		super(props);

		this.state = {
			visible: false
		};

		// Initial show
		setTimeout(() => {
			this.setState({
				visible: true
			});
		}, this.props.animationDuration);

		// Auto hide
		setTimeout(() => {
			this.setState({
				visible: false
			});
		}, this.props.duration + this.props.animationDuration);
	}

	getIcon() {
		if (this.props.icon) {
			return this.props.icon;
		}

		let icon = '';

		switch (this.props.type) {
		case 'error':
			icon = 'exclamation circle';
			break;
		case 'info':
			icon = 'info circle';
			break;
		case 'success':
		default:
			icon = 'check circle';
			break;
		case 'warning':
			icon = 'exclamation triangle';
			break;
		}

		return icon;
	}

	hide() {
		this.setState({
			visible: false
		});
	}

	render() {
		return (
			<SemanticTransition
				visible={this.state.visible}
				animation={this.props.animation}
				duration={this.props.animationDuration}
				mountOnShow
				unmountOnHide
			>
				<div>
					<SemanticMessage
						className={styles.Toast}
						content={this.props.content}
						icon={this.getIcon()}
						onDismiss={() => this.hide()}
						floating
						compact
						{...{ [this.props.type]: true }}
					/>
				</div>
			</SemanticTransition>
		);
	}
}
