import { ICompileService, IController, ISCEService, IScope, ITimeoutService } from 'angular';
import { Magento2EcmsBlockApiService } from './magento2.ecms.block.api.service';
import { IMenu, Menu } from './megamenu.menu';
import { ScopedCompileFactory } from '../ScopedCompile';
import { DomUtils } from '../DomUtils';


/**
 * Controller holding the application-logic for <megamenu-component>
 */
export class MegamenuController implements IController {

  public menus: Array<IMenu> = [];
  public shutter: JQLite;

  constructor(
    public $element: JQLite,
    private readonly magento2EcmsBlockApiService: Magento2EcmsBlockApiService,
    private readonly $sce: ISCEService,
    private readonly $timeout: ITimeoutService,
    private readonly $compile: ICompileService,
    private readonly $scope: IScope
  ) {
  }

  public $onInit() {
    this.$element.addClass('megamenu-container');
    this.shutter = this.$element.find('.megamenu-shutter');
  }

  public $postLink() {
    let $menus = this.$element.find('[data-category]');

    angular.forEach($menus, ($menu: HTMLElement) => {
      let menuScope = this.$scope.$new(true);
      (menuScope as any).categoryUrl = ($menu.querySelector('a[href].level-top') as HTMLLinkElement || { href: undefined }).href;

      let menu = new Menu(
        $menu,
        this.$timeout,
        ScopedCompileFactory(this.$compile, menuScope),
        this.magento2EcmsBlockApiService,
        this._onMenuOpen.bind(this),
        this._onMenuClose.bind(this)
      );

      if (menu.category.length > 0) {
        menu
          .fetch()
          .then(() => {
            this.menus.push(menu);
          })
          .catch((reason) => {
            // console.error(reason);
          });
      }
    });
  }

  private _onMenuOpen(menu: IMenu) {
    this.menus.forEach((otherMenu) => {
      if (otherMenu !== menu) {
        otherMenu.close();
      }
    });
    this._showShutter(menu.target);
  }

  private _onMenuClose(menu: IMenu) {
    this._hideShutter();
  }

  private _showShutter(target: HTMLElement = this.$element[0]) {
    let bounding = DomUtils.getOffsetBounding(target);
    this.shutter
      .css('top', bounding.top + bounding.height)
      .removeClass('hidden');
  }

  private _hideShutter() {
    for (let i = 0, menu; (menu = this.menus[i]); i++) {
      if (menu.active) {
        return;
      }
    }
    this.shutter.addClass('hidden');
  }
}
