import { Component, ElementRef, Input, OnInit, OnDestroy, ChangeDetectionStrategy } from '@angular/core';
import { ModalService } from './modal.service';

@Component({
  selector: 'app-modal',
  template: `
    <div class="app-modal" [ngClass]="{ 'higher-order': higerOder }">
      <div class="app-modal-body" [ngClass]="{ 'higher-order': higerOder }">
        <ng-content></ng-content>
      </div>
      <div class="app-modal-background" [ngClass]="{ branch: branch }"></div>
    </div>
  `,
  styleUrls: ['./modal.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ModalComponent implements OnInit, OnDestroy {
  @Input() id: string;
  @Input() branch = false;
  @Input() higerOder = false;
  private element: any;

  constructor(private modalService: ModalService, private el: ElementRef) {
    this.element = el.nativeElement;
  }

  ngOnInit(): void {
    const modal = this;

    // ensure id attribute exists
    if (!this.id) {
      console.error('modal must have an id');
      return;
    }

    // move element to bottom of page (just before </body>) so it can be displayed above everything else
    document.body.appendChild(this.element);

    // close modal on background click
    this.element.addEventListener('click', function (e: any) {
      if (e.target.className === 'app-modal') {
        modal.close();
      }
    });

    // add self (this modal instance) to the modal service so it's accessible from controllers
    this.modalService.add(this);
  }

  // remove self from modal service when directive is destroyed
  ngOnDestroy(): void {
    this.modalService.remove(this.id);
    this.element.remove();
  }

  // open modal
  open(): void {
    this.element.children[0].style.display = 'block';
    document.body.classList.add('app-modal-open');
  }

  // close modal
  close(): void {
    this.element.children[0].style.display = 'none';
    document.body.classList.remove('app-modal-open');
  }
}
