import React from 'react';
import DefaultStyles from './styles';
import storify from '../../UtilitiesFunctions/storify';
import {Row,Column} from '../baseComponents'
import ReactModal from 'react-modal';


class DumbModal extends React.Component{

	getParent = () => document.querySelector('#rivigo-modal-'+this.props.name)

	render(){
		const {storifyActions:{openModal,closeModal},storifyState,name,...rest} = this.props
		const modal = storifyState[name]
		const data = modal && modal.data || {}
		const {height=400, width=500, StyleWrapper,Component,Heading} = data
		const Styles = typeof StyleWrapper=='function' ? props => <StyleWrapper>{props.children}</StyleWrapper> :props => <div>{props.children}</div>
		return(
			<DefaultStyles height={height} width={width}>
				<Styles>
					<div id={`rivigo-modal-${name}`}>
						<ReactModal
			    			isOpen = {modal && modal.visibility}
			    			parentSelector={this.getParent}
				    	>
						{
							modal && modal.visibility?
							([
								typeof Heading=='function' ? Heading(data,name) : defaultHeader(data,name)
								,<Component ref={data.refCb} {...rest} {...data}/>
							]):
							null
						}
				    	</ReactModal>
					</div>
				</Styles>
			</DefaultStyles>
		)
	}
}

var defaultHeader = ({Heading,showClose,onCloseClick},name) => <div className='modal-header'>
    <div className="header-text">{Heading || ''}</div>
    {
	    showClose!==false &&
	    <div className="closeBtn">
	        <i className="material-icons" 
        		onClick={()=>{
	        		if(onCloseClick) onCloseClick()
	        		closeModal(name)
        	}}>&#xE14C;</i>
	    </div> || null
    }
</div>

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        closeModals()
    }
};

const actions = (store,render) => ({
	openModal : (key, data) => {
		if(!store[key]) store[key] = {}
		store[key].data=data 
		store[key].visibility=true
		render()
	},
	closeModals : () => {
		for(var key in store){
			if(store[key].visibility){
				store[key].visibility = false
				break
			}
		}
		render()
	},
	closeModal : (key) => {
		store[key].visibility=false
		render()
	}
})

const {Wrap, openModal, closeModal, closeModals} = storify(DumbModal, actions, {})
const Modal = Wrap
export {Modal, openModal, closeModal}