import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  OnDestroy,
  ElementRef,
  Renderer2
} from '@angular/core';
import { MatMenuPanel, MatMenuTrigger, MatButton } from '@angular/material';
import { Subscription } from 'rxjs';
import { NGXLogger } from 'ngx-logger';

@Component({
  selector: 'ucap-split-button',
  templateUrl: './split-button.component.html',
  styleUrls: ['./split-button.component.scss']
})
export class SplitButtonComponent implements OnInit, OnDestroy {
  @Input()
  menu: MatMenuPanel;

  @Input()
  disabled: boolean;

  @Output()
  buttonClick = new EventEmitter<MouseEvent>();

  @Output()
  splitClick = new EventEmitter<MouseEvent>();

  @ViewChild('matMenuTrigger', { static: true })
  private matMenuTrigger: MatMenuTrigger;

  // tslint:disable-next-line: variable-name
  private _handleClick: (event: MouseEvent) => void;
  private menuCloseSubscription: Subscription;
  splitOpened = false;

  constructor(
    private elementRef: ElementRef<HTMLElement>,
    private logger: NGXLogger
  ) {}

  ngOnInit() {
    this.menuCloseSubscription = this.menu.close.subscribe(() => {
      this.matMenuTrigger._handleClick = e => {};
      this.splitOpened = false;
    });
    this._handleClick = this.matMenuTrigger._handleClick;
    this.matMenuTrigger._handleClick = e => {};
  }

  ngOnDestroy(): void {
    if (!!this.menuCloseSubscription) {
      this.menuCloseSubscription.unsubscribe();
    }
  }

  onClick(event: MouseEvent) {
    this.buttonClick.emit(event);
  }

  onClickSplit(event: MouseEvent) {
    this.matMenuTrigger._handleClick = this._handleClick;
    this.splitOpened = true;
    this.splitClick.emit(event);
  }
}
