import React from "react";
import Link from "next/link";
import { connect } from "react-redux";
import { getContractEvents, getContractFines, getContractInfo, } from "../../../../actions";

class InnerMenu extends React.Component
{
	constructor(props)
	{
		super(props);
		this.menuRef = React.createRef();

		this.state = {
			loaded: false, 
			loading: true, 
			menuOpened: false, 
			events_loaded: false, 
			contracts_info: {}, 
			contract_events: {}, 
			contract_fines: {}, 
		};
	}

	static getDerivedStateFromProps(nextProps, prevState) 
	{
		return {
			events_loaded: nextProps.events_loaded, 
			contracts_info: nextProps.contracts_info, 
			contract_events: nextProps.contract_events, 
			contract_fines: nextProps.contract_fines, 
		};
	}

	componentDidMount()
	{
		console.log("Contact", "InnerMenu", "componentDidMount()");

		const { loaded, loading, events_loaded, contracts_info, contract_events, contract_fines } = this.state;

		if(!loaded && events_loaded && 
			contracts_info !== undefined && Object.keys(contracts_info).length > 0
		) {
			this.setState({ loaded: true }, () => 
			{
				this._loadMenu();
			});
		}
	}

	componentDidUpdate(prevProps, prevState)
	{
		const { loaded, events_loaded, contracts_info, contract_events, contract_fines } = this.state;

		if(!loaded && events_loaded && contracts_info !== undefined && Object.keys(contracts_info).length > 0) 
		{
			this.setState({ loaded: true }, () => 
			{
				this._loadMenu();
			});
		}
	}

	_loadMenu = () => 
	{
		console.log("Contract", "InnerMenu", "_loadMenu()");

		const { number, dispatch } = this.props;
		const { contracts_info, contract_events, contract_fines } = this.state;

		Promise.all([ 
			new Promise((resolve) => 
			{
				if(contracts_info[ number ] === undefined)
				{
					getContractInfo({ dispatch, number })
					.then(() => { console.log(11); resolve(); })
					.catch(() => { console.log(12); resolve(); });
				}
				else
				{
					resolve();
				}
			}), 
			new Promise((resolve) => 
			{
				if(contract_events[ number ] === undefined)
				{
					getContractEvents({ dispatch, contract: number })
					.then(() => { console.log(21); resolve(); })
					.catch(() => { console.log(22); resolve(); });
				}
				else
				{
					resolve();
				}
			}), 
			new Promise((resolve) => 
			{
				if(contract_fines[ number ] === undefined)
				{
					getContractFines({ dispatch, contract: number })
					.then(() => { console.log(31); resolve(); })
					.catch(() => { console.log(32); resolve(); });
				}
				else
				{
					resolve();
				}
			}), 
		])
		.then(() => 
		{
			let l = 0;
			let m = 0;
			const menu = [ "payments", "change", "services", "agreement", "documents", "materials", "events", "fines" ];

			for(let i in menu)
			{
				if(this.props.router.asPath.indexOf(menu[i]) > -1)
				{
					m = i;
				}
			}

			this.setState({ loading: false }, () => 
			{
				if(this.menuRef.current !== null)
				{
					for(let i = 0; i < m; i++)
					{
						if(this.menuRef.current.children[i] !== undefined)
						{
							l = l + this.menuRef.current.children[i].getBoundingClientRect().width;
						}
					}
	
					if(this.menuRef.current !== null)
					{
						this.menuRef.current.scrollLeft = l - 50;
					}
				}
			});
		});
	}

	_handle_onToggleMenu = () => 
	{
		this.setState({
			menuOpened: !this.state.menuOpened, 
		});
	}

	_getActiveLink = (route) => 
	{
		if (route.indexOf("/payments") > -1) return "График платежей";
		if (route.indexOf("/change") > -1) return "Изменить график";
		if (route.indexOf("/services") > -1) return "Дополнительные услуги";
		if (route.indexOf("/agreement") > -1) return "Документы по договору";
		if (route.indexOf("/documents") > -1) return "Закрывающие документы";
		if (route.indexOf("/materials") > -1) return "Документы по ФСБУ 25/2018";
		if (route.indexOf("/events") > -1) return "События по договору";
		if (route.indexOf("/fines") > -1) return "Штрафы ГИБДД";

		return null;
	}

	_getFinesCount = () => 
	{
		const { number, } = this.props;
		const { contract_fines } = this.state;
		let c = 0;

		if(contract_fines[number] !== undefined && contract_fines[number] !== null)
		{
			for(let i in contract_fines[number])
			{
				if(contract_fines[number][i].status_code === "NotPaid" || contract_fines[number][i].status_code === "PaidEvolution")
				{
					c++;
				}
			}
		}

		return c;
	}

	render()
	{
		const { number, status } = this.props;
		const { loading, menuOpened, contracts_info, contract_events, contract_fines } = this.state;
		const count_events = contract_events !== undefined && contract_events[number] !== undefined && contract_events[number] !== null ? Object.keys(contract_events[number]).length : 0;
		const count_fines = this._getFinesCount();

		if(!loading)
		{
			console.log("contracts_info", contracts_info);
		}

		return (
			<aside>
				<button className="nav_toggle" onClick={ this._handle_onToggleMenu }>
					{ this.props.router && this._getActiveLink(this.props.router.asPath) }
				</button>
				{ !loading && (
					<ul className={ menuOpened ? "aside_nav open" : "aside_nav" } ref={ this.menuRef }>
						<li>
							<Link href={`/contract/${ number }/payments`} shallow>
								<a className={ this.props.router && this.props.router.asPath.indexOf("payments") > -1 ? "active" : "" }>График платежей</a>
							</Link>
						</li>
						{ contracts_info !== undefined && contracts_info[ number ] !== undefined && contracts_info[ number ].status !== undefined && contracts_info[ number ].status !== null && [46, 36, 37, 35].indexOf(contracts_info[ number ].status) > -1 && (
							<li>
								<Link href={`/contract/${ number }/change`} shallow>
									<a className={ this.props.router && this.props.router.asPath.indexOf("change") > -1 ? "active" : "" }>Изменить график</a>
								</Link>
							</li>
						) }
						<li>
							<Link href={`/contract/${ number }/services`} shallow>
								<a className={ this.props.router && this.props.router.asPath.indexOf("services") > -1 ? "active" : "" }>Дополнительные услуги</a>
							</Link>
						</li>
						<li>
							<Link href={`/contract/${ number }/agreement`} shallow>
								<a className={ this.props.router && this.props.router.asPath.indexOf("agreement") > -1 ? "active" : "" }>Документы по договору</a>
							</Link>
						</li>
						<li>
							<Link href={`/contract/${ number }/documents`} shallow>
								<a className={ this.props.router && this.props.router.asPath.indexOf("documents") > -1 ? "active" : "" }>Закрывающие документы</a>
							</Link>
						</li>
						<li>
							<Link href={`/contract/${ number }/materials`} shallow>
								<a className={ this.props.router && this.props.router.asPath.indexOf("materials") > -1 ? "active" : "" }>Документы по ФСБУ 25/2018</a>
							</Link>
						</li>
						<li>
							<Link href={`/contract/${ number }/events`} shallow>
								<a className={ this.props.router && this.props.router.asPath.indexOf("events") > -1 ? "active" : "" }>События по договору { count_events > 0 && (<span>{ count_events }</span>) }</a>
							</Link>
						</li>
						{ contract_fines !== undefined && contract_fines[number] !== undefined && contract_fines[number] !== null && count_fines > 0 && (
							<li>
								<Link href={`/contract/${ number }/fines`} shallow>
									<a className={ this.props.router && this.props.router.asPath.indexOf("fines") > -1 ? "active" : "" }>Штрафы ГИБДД{ count_fines > 0 && (<span>{ count_fines }</span>) }</a>
								</Link>
							</li>
						) }
					</ul>
				) }
			</aside>
		)
	}
}

function mapStateToProps(state, ownProps) 
{
	return {
		events_loaded: state.events.loaded, 
		contracts_info: state.contracts_info, 
		contract_events: state.contract_events, 
		contract_fines: state.contract_fines, 
	};
}

export default connect(mapStateToProps)(InnerMenu);