const router = require('./router');
const Box = require('./box');
const head = document.head;

module.exports = class Modal extends DOM {
	constructor(props){
		super(props);
		this.state = {dialog: []};
	}
	link(a, push){
		router(a, false, function(data){
			var {main, meta, event} = data;

			app.html(main).emit(event, a.dataset);

			document.title = meta.title;

			for(let i in meta){
				head.findAll('meta[name$="'+ i +'"]').each(e => e.content = meta[i])
			}

			if(push !== false || a.href !== document.location.href) history.pushState(null, null, a.href);
		})
	}
	componentWillMount(){
		this.on('link', this.link);
		this.on('delete_box', box => box && !box.remove() || this.link(document.location.href, false));
	}
	render(){
		return <div className="fixed empty-0 modal">
			{this.state.dialog.push(options => {
				var box = DOM.x(Box, options), 
					link = options.link || options.url ? DOM.x('a', {href: options.url}) : null;

				if(link) setTimeout(router, 0, link, true, data => box.setState(data));

				return box;
			})}
		</div>
	}
}