import React from "react";
import Link from "next/link";

const menu = [
	{id: 1, type: "phone", name: "Номер телефона", link: "/settings/phone"},
	{id: 2, type: "password", name: "Пароль", link: "/settings/password"},
	{id: 3, type: "admin", name: "Настройки доступа", link: "/settings/admin"},
]

export default class InnerMenu extends React.Component
{
	constructor(props)
	{
		super(props);
		this.state = {
			menuOpened: false,
		};
		
		this.menuRef = React.createRef();
	}

	componentDidMount()
	{
		let l = 0;
		let m = 0;
		const menu = [ "phone", "password", "admin" ];

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

		for(let i = 0; i < m; i++)
		{
			l = l + this.menuRef.current.children[i].getBoundingClientRect().width;
		}

		this.menuRef.current.scrollLeft = l - 50;
	}

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

	_getActiveLink = (route) => 
	{
		if (route.indexOf("/phone") > -1) return "Номер телефона";
		if (route.indexOf("/password") > -1) return "Пароль";
		if (route.indexOf("/admin") > -1) return "Настройки доступа";

		return null;
	};

	scrollToCategory = id => {
		
	};

	render()
	{
		const { user, observer } = this.props;
		const { menuOpened, } = this.state;

		return (
			<aside>
				<button className="nav_toggle" onClick={ this._handle_onToggleMenu }>
					{ this.props.router && this._getActiveLink(this.props.router.asPath) }
				</button>
				<ul className={ menuOpened ? "aside_nav open" : "aside_nav" } ref={ this.menuRef }>
					{ user !== undefined && user !== null && menu.map(item => 
					{
						if(item.type === "admin" && !observer && !user.is_admin) { return null; }

						return (
							<li key = {item.id} ref={this[item.id]}>
								<Link 
									href={item.link}
									shallow
								>
									<a className={ this.props.router && this.props.router.route === item.link ? "active" : "" }>{item.name}</a>
								</Link>
							</li>
						)
					}) }
				</ul>
			</aside>
		)
	}
}