import React, { Component } from 'react';
import PropTypes from 'prop-types';

import emitter from 'lib/event-emmiter';
import { injectIntl } from 'react-intl';


let mql = window.matchMedia(`(min-width: 820px)`);

require('styles/layout.scss');
require('./sideLayout.scss');


class SideMenuLayout extends Component {

    constructor(props) {
        super(props);
        this.state = {
            docked: true,
            open: true
        };
        
        this.mediaQueryChanged = this.mediaQueryChanged.bind(this);
        
        this.onSetSidebarOpen = this.onSetSidebarOpen.bind(this);
        this.handleLogout = this.handleLogout.bind(this);
        this.renderMenuItems = this.renderMenuItems.bind(this);
        this.handleMenuClick = this.handleMenuClick.bind(this);
    }
    
    onSetSidebarOpen(open) {
        if (this.state.docked && typeof this.props.onMenuStateChanged == "function") {
            this.props.onMenuStateChanged(open);
        }
        this.setState({ open: open });
    }

    componentWillMount() {
        mql.addListener(this.mediaQueryChanged);
        this.mediaQueryChanged();

        let docked = mql.matches;
        let open = this.state.open;
        if (docked && typeof this.props.menuOpen != "undefined") {
            open = this.props.menuOpen;
        }
        this.setState({ docked, open });
    }

    componentWillUnmount() {
        mql.removeListener(this.mediaQueryChanged);
    }

    mediaQueryChanged() {
        let m = mql.matches;
        this.setState({ docked: m });
    }

    handleLogout(e) {
    	let onLogout = this.props.onLogout;
    	if (typeof onLogout === "function") {
    		e.preventDefault();	
    		onLogout();
    	}
    }

    renderMenuItems() {
        const 
            menuItems = this.props.menuItems,
            router = this.context.router,
            location = router.location.pathname;

        if (!Array.isArray(menuItems)) {
            return null;
        }

        //get active 
        let active = "", r;
        for (let i = 0; i < menuItems.length; i++) {
            if (Array.isArray(menuItems[i].routes)) {
                for (let j = 0; j < menuItems[i].routes.length; j++) {
                    r = menuItems[i].routes[j];
                    if (r && location.startsWith(r) && r.length > active.length) {
                        active = menuItems[i].route;
                    }
                }
            } else {
                r = menuItems[i].route;
                if (r && location.startsWith(r) && r.length > active.length) {
                    active = r;
                }
            }
        }

        return menuItems.map((menu, i) => (
            <button key={ menu.id || i } className={ menu.route == active ? "side-menu-item active" : "side-menu-item" } href={ menu.route || "" } onClick={ this.handleMenuClick(menu) } title={ menu.title || menu.id }>
                { menu.icon || menu.iconName ? (<i className={`icon ${menu.iconName || ""}`}>{ menu.icon }</i>) : null } <span className="side-menu-item-label">{ menu.title || menu.id }</span>
            </button>
        ));
    }

    handleMenuClick(item) {
        let {
            router
        } = this.context;

        return (e) => {
            e.preventDefault();
            emitter.emit("sideMenuClicked", item);

            if (!this.state.docked) {
                this.onSetSidebarOpen(false);
            }

            if (typeof item.action === "function") {
                item.action();
                return;
            }

            if (item.route) {
                router.push(item.route);
            }

        }
    }


    render() {
        let { docked, open } = this.state;
        let { menuTopSection, menuItems } = this.props;

        return (
            <div className={ `side-menu-layout ${ open ? "open" : "closed" } ${ docked ? "docked" : "overlay" }` }>
                {/* main content */}
                <div className="layout-content">
            	   { this.props.children }
                </div>

                <header className="top-menu-bar">
                </header>

	  			{/* sidebar toggle button */}
                <div className="side-menu-overlay" onClick={ () => this.onSetSidebarOpen(false) }>
                </div>

                <div className={ `side-menu` }>
                    <div className="side-menu-info-section">
                        { menuTopSection }
                    </div>
                    <div className="side-menu-items">
                        { this.renderMenuItems() }
                    </div>
                </div>


                <button className="side-menu-button" onClick={()=> { this.onSetSidebarOpen(!open); } }>
                    <span className="icon">&#xf0c9;</span>
                </button>

            </div>
        );
    }
};

SideMenuLayout.contextTypes = {
  router: React.PropTypes.object.isRequired
};


export default injectIntl(SideMenuLayout);
