import { AfterViewInit, ViewChild, ChangeDetectorRef, Component, ElementRef, Input, OnInit, OnDestroy, TemplateRef } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { NotificationService } from '@shared/ui-api/notification.service';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { ActionTypes } from '@objects-view/actions/action-types';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { UiHelper } from '@shared/ui-api/helpers/ui-helper';

@Component({
  selector: 'app-common-dialog',
  templateUrl: './common-dialog.component.html',
  styleUrls: ['./common-dialog.component.scss']
})
export class CommonDialogComponent implements OnInit, OnDestroy, AfterViewInit {
  @ViewChild('dialogContainer') dialogContainer: ElementRef;
  @Input() dialogContent: TemplateRef<any>;
  @Input() dialogRef: MatDialogRef<IBaseDialog>;
  @Input() addCancelDialogButton = true;
  @Input() unlimitedWidth = false;
  @Input() skipInputFocus = false;
  @Input() limitTitle = false;
  showScrollbar = false;
  dialogContainerObserver: ResizeObserver;
  public actionTypes = ActionTypes;

  constructor(
    public notificationService: NotificationService,
    public refreshService: RefreshService,
    private elementRef: ElementRef,
    private changeDetectorRef: ChangeDetectorRef,
  ) { }

  ngOnInit(): void {
  }

  ngAfterViewInit() {
    if (!this.skipInputFocus) {
      const focusableInputFound = UiHelper.focusAndSelectFirstInput(this.elementRef, this.changeDetectorRef);
      if (!focusableInputFound) {
        // we did not find any input we'd want to focus & select, focus the primary button instead
        UiHelper.focusPrimaryButton(this.elementRef);
      }
    }

    // observe dialog height and make sure scroll is shown only when needed
    this.dialogContainerObserver = new ResizeObserver((entries: Array<ResizeObserverEntry>) => {
      if (entries && entries.length) {
        this.showScrollbar = this.dialogContainer.nativeElement.offsetHeight >= (60 / 100 * window.innerHeight);
      }
    });
    this.dialogContainerObserver.observe(this.dialogContainer.nativeElement);
  }

  public closeDialog() {
    this.dialogRef.close(false);
  }

  ngOnDestroy() {
    if (this.dialogContainerObserver && this.dialogContainerObserver.unobserve) {
      this.dialogContainerObserver.unobserve(this.dialogContainer.nativeElement);
      this.dialogContainerObserver = null;
    }
  }

}
