import React from "react";
import Manager from "../../Manager";

export default class AccountLayout extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
			messages: [], 
		}
	}

	componentDidMount()
	{
		if(window !== undefined)
		{
			window.addEventListener("_track", this._handle_onTrack);
			window.addEventListener("_move", this._handle_onMove);
			window.addEventListener("_message", this._handle_onMessage);

			const store = global.store.getState();
			const { company, user } = store;

			console.log("LAYOUT", "CDM", { store });

			const payload = {
				userID: user.email !== undefined && user.email !== null && user.email !== "" ? user.email : user.phone, 
				companyID: company.active, 
			};

			if(payload.companyID !== undefined && payload.companyID !== null && payload.companyID !== "")
			{
				console.log("LAYOUT", "CDM", { payload });
				ym(process.env.YANDEX_METRIKA_ID, 'userParams', payload);
			}
		}

		console.log("CDM", { state: this.state });
	}

	componentWillUnmount()
	{
		if(window !== undefined)
		{
			window.removeEventListener("_track", this._handle_onTrack);
			window.removeEventListener("_move", this._handle_onMove);
			window.removeEventListener("_message", this._handle_onMessage);
		}
	}

	_handle_onTrack = (event) => 
	{
		//event.detail.path
		console.log("LAYOUT", "_handle_onTrack", { event, props: this.props });

		console.log({ ym });
	}

	_handle_onMove = (event) => 
	{
		this.props.router.push(event.detail.path);
	}

	_handle_onMessage = (event) => 
	{
		if(process.env.CLIENT_SHOW_ERROR_MESSAGE)
		{
			const messages = [ ...this.state.messages ];
			messages.push(event.detail);
			this.setState({ messages });
		}
	}

	_handle_onMessageRemove = (index) => 
	{
		if(process.env.CLIENT_SHOW_ERROR_MESSAGE)
		{
			const messages = [ ...this.state.messages ];
			messages.splice(index, 1);
			this.setState({ messages });
		}
	}

	render()
	{
		const { messages } = this.state;

		return (
			<main>
				<section>
					<div className="clear"></div>
					<div className="overflow">
						<div className="container">
							{ this.props.children }
						</div>
					</div>
				</section>
				<Manager/>
				{ messages.length > 0 && (
					<div className="messages_overlay">
						{ messages.map((message, index) => (
							<div className={ `overlay_message_${ message.type }` } key={ index }>
								<h4>{ message.title }</h4>
								<p>{ message.content }</p>
								<div className="button" onClick={ () => this._handle_onMessageRemove(index) }></div>
							</div>
						))}
					</div>
				) }
			</main>
		)
	}
}