import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import CircularProgress from 'material-ui/CircularProgress';
import {ControlledRenderer} from '../../Utils'


const defaultLoader = loaderSize => <CircularProgress size={loaderSize} thickness={Number(loaderSize/20)} />

export default class LoaderWrapper extends React.Component{

	refCb = el => {
		this.childEl=el
		this.setState({})
	}

	render() {
		const height = this.childEl && this.childEl.clientHeight || 0
		const width = this.childEl && this.childEl.clientWidth || 0
		const loaderSize = Number(Math.min(width,height)/2)
		return(
			<div style={{ position:'relative' }}>
				{
					this.props.visibility &&
					<div style={{
						position:'absolute',
						top:'0px', 
						left:'0px',
						height:`${height}px`, 
						width:`${width}px`,
						background: 'rgba(0,0,0,0.1)',
    					zIndex : 2,
    					display : 'flex',
    					justifyContent : 'center',
    					alignItems : 'center'
					}}>
						{this.props.loader ? this.props.loader(height,width) : defaultLoader(loaderSize)}
					</div>
				}
				<div ref={this.refCb}>
					<ControlledRenderer
						shouldRender={!this.renderAgain}
						render={this.props.children} />
				</div>
			</div>
		)
	}

	componentDidUpdate = ()  => {
		this.renderAgain = !this.renderAgain
		if(this.renderAgain){
			this.setState({})
		}
	}
}

LoaderWrapper.propTypes = {
  visibility: PropTypes.bool.isRequired,
  loader : PropTypes.func
};