import { Component, Listen, Prop, State } from '@stencil/core';

@Component({
  tag: 'ion-menu-toggle',
})
export class MenuToggle {
  @Prop({ context: 'document' })
  doc!: Document;

  @State() visible = false;

  /**
   * Optional property that maps to a Menu's `menuId` prop.
   * Can also be `left` or `right` for the menu side.
   * This is used to find the correct menu to toggle
   */
  @Prop() menu?: string;

  /**
   * Automatically hides the content when the corresponding menu is not active
   */
  @Prop() autoHide = true;

  componentDidLoad() {
    this.updateVisibility();
  }

  @Listen('click')
  async onClick() {
    const menuCtrl = await getMenuController(this.doc);
    if (menuCtrl) {
      const menu = menuCtrl.get(this.menu);
      if (menu && menu.isActive()) {
        return menuCtrl.toggle(this.menu);
      }
    }
    return false;
  }

  @Listen('body:ionMenuChange')
  @Listen('body:ionSplitPaneVisible')
  async updateVisibility() {
    const menuCtrl = await getMenuController(this.doc);
    if (menuCtrl) {
      const menu = menuCtrl.get(this.menu);
      if (menu && menu.isActive()) {
        this.visible = true;
        return;
      }
    }
    this.visible = false;
  }

  hostData() {
    const hidden = this.autoHide && !this.visible;
    return {
      'hidden': hidden
    };
  }
}

function getMenuController(doc: Document): Promise<HTMLIonMenuControllerElement|undefined> {
  const menuControllerElement = doc.querySelector('ion-menu-controller');
  if (!menuControllerElement) {
    return Promise.resolve(undefined);
  }
  return menuControllerElement.componentOnReady();
}
