import Search from "./search/search.js";
import MenuItem from "./menu-item.js";

export const MENU_SELECTOR = '#menu';

/**
 * Handles site Menu functions other than basic expand/collapse and location view.
 * @see MenuEssential For the basic menu functionality. Separated to preserve basic support on legacy browser.
 * @see Template/ops_Page/ops_Page_Sidebar.tpl Menu render.
 */
export default class Menu {
	/**
	 * @param {Object.<string, MenuItemObj>} structure Menu JSON structure/tree.
	 */
	constructor(structureObj) {
		this.itemArr = [];
		for (let [name, itemObj] of Object.entries(structureObj)){
			this.itemArr.push(new MenuItem(this, itemObj, name));
		}
		this.element = document.querySelector(MENU_SELECTOR);
		this.search = new Search(this);
		
		// Global key listener for menu functions.
		document.addEventListener('keydown', event => {
			// Check for "Active Menu" keyboard shortcut: Ctrl+Q or Alt+/ 
			if (event.ctrlKey && event.key === 'q' || event.altKey && event.key === '/') {
				// If the search is already active:
				let isActive = this.element.classList.contains('expanded') && this.search.isActive();
				// Activate or deactivate the menu & search:
				this.search.setActive(!isActive);	
				this.element.classList.toggle('expanded', !isActive);
				document.getElementById('logo_image').classList.toggle('rotate');
				this.search.focusTextbox(!isActive);
				
				event.stopPropagation();
				event.preventDefault();
				
				return;
			}
			// If the menu is already expanded, pass key input to the search textbox.
			if (this.element.classList.contains('expanded')) {
				// Delegate key to Menu Search:
				this.search.onKeyDown(event);
			}
		});
	}

	/**
	 * @return {Element}
	 */
	getElement() {
		return document.querySelector(MENU_SELECTOR);
	}

	/**
	 * @param {boolean} sticky
	 */
	setHeaderSticky(sticky=true) {
		document.querySelector(MENU_SELECTOR).classList.toggle('sticky-header', sticky);
	}
	/**
	 * @return {MenuItem[]}
	 */
	getItems() {
		return this.itemArr;
	}
	isFiltered() {
		return Boolean(this.search.getFilter());
	}
	scrollToTop() {
		if (this.element.scrollTop !== 0) {
			this.element.scroll({top:0});
		}
	}
	/**
	 * Collapse all expanded menu items. 
	 */
	resetItemStates() {
		// Remove semitransparent styling:
		this.element.querySelectorAll('dt.semitransparent').forEach(elem=> elem.classList.remove('semitransparent'));
		// Collapse all items:
		this.element.querySelectorAll('dt.expanded').forEach(elem => {
			elem.classList.remove('expanded');
			// Reset the child
			let childContainer = MenuItem.getChildContainer(elem);
			if (childContainer){
				childContainer.style.display = 'none';
			}
		});
		// Ensure root items are visible
		for (let item of this.itemArr) {
			item.setVisible();
		}
	}
}
