import React, { Component } from 'react';

import { Modal, ModalTitle, ModalContent, ModalButtonBar } from 'lib/components';


class Alert extends Component {

	constructor(props) {
		super(props);

		this.showAlert = this.showAlert.bind(this);
		this.onButtonPressed = this.onButtonPressed.bind(this);
		this.dismiss = this.dismiss.bind(this);

		this.state = {
			visible: false
		};
	}


	componentWillMount() {
		global._showAlert = this.showAlert;
	}


	onButtonPressed(handler) {
		return (e) => {
			typeof handler === "function" && handler();
			this.dismiss();
		}
	}


	showAlert(title, content, buttons) {
		this.setState({ visible: true, title, content, buttons });
	}


	dismiss() {
		const { onDismiss } = this.props;
		typeof onDismiss === "function" && onDismiss();
		this.setState({ visible: false });
	}


	render() {
		const {
			buttons,
			content,
			title,
			visible
		} = this.state;

		if (!visible) {
			return null;
		}

		return (
			<Modal show={ visible } closeButton onClose={ this.dismiss }>
				<ModalTitle>{ title }</ModalTitle>
				<ModalContent>{ content }</ModalContent>
				<ModalButtonBar>
					{ !Array.isArray(buttons) ? null : 
						buttons.map((button, key) => <button key={key} type="button" className={ button.primary ? "primary" : "" } onClick={ this.onButtonPressed(button.onPress) }>{ button.text }</button>)
					}
				</ModalButtonBar>
			</Modal>
		);
	}

}

export default {
	alert: (title, content, buttons) => {
		if (typeof global._showAlert !== 'function') {
			if (process.env.NODE_ENV !== 'production') {
				console.error("Cannot display alert. Chceck whether Alert.Component is included in the layout.")
			}
			return;
		}
		global._showAlert(title, content, buttons)
	},
	Component: Alert
};
