const State = require('./state');
const className = ['default', 'primary', 'success'];
const submit = <input type="submit" name="submit" hidden={true}/>;


/**
 *	Header {ObjectDOM | HTML}
 *	Button {Object}: 	{cancel(){}, save(form_data){}}
 */

module.exports = class Box extends DOM {
	constructor(props){

		let info = new State(props);

		super(info.props);

		this.state = info.states;

		this.button = !info.button ? [] : info.button.toarray(function(action, value){
			return {
				action, 
				value, 
				text: lang[value] || value.replace(value[0], value[0].toUpperCase())
			}
		});
	}
	submit(e) {
		e.preventDefault();

		var form = e.target, 
			data = $.data(form),
			button = this.button.get({ value: form.action.value });

		delete data.action;
		if(button.action) button.action(data);
		this.remove(); 
	}
	remove(){
		this.dom.remove();
	}
	static change(){
		submit.click() 
	}

	render(){
		return (
			<div className="modal-container">
				<div className="absolute bg-dark w-100 h-100" style="opacity:0.4;top:0;left:0;" onclick={this.props.close ? this.remove.bind(this) : null} />
				<form
					className={this.props.box + "-box absolute bg-white center p-0 m-0 " + this.props.className}
					onsubmit={this.submit.bind(this)}
					style={this.props.style}>

					<header className="empty-0 relative">
						{this.state.meta.update(meta => <h3 className="bold m-0 pr-5">{meta.title}</h3>)}
						{this.props.close ? <a className="g g-remove absolute h-100" onclick={this.remove.bind(this)}/> : null}
					</header>

					{this.state.main.update(text => <section className="empty-0" style="height:calc(100% - 37px);">{text}</section>)}

					<footer className="empty-0 text-right b-top" style="height: 3.4rem;">
						{this.button.map((btn, i) => 
							<label style="margin: 0 0 0 0.5rem;">
								<input type="radio" name="action" onchange={Box.change} value={btn.value} hidden={true}/>
								<span className={"btn btn-sm btn-" + className[i%2]}>{btn.text}</span>
							</label>
						)}
					</footer>

					{submit}
				</form>
			</div>
		)
	}
}