import { Component, ChangeDetectionStrategy, OnInit, TemplateRef, Type } from '@angular/core';
import { UiModalRef } from './defs/modal-ref';

@Component({
  selector: 'ui-modal',
  templateUrl: 'modal.component.html',
  styleUrls: ['modal.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UiModalComponent implements OnInit {
  contentType: 'template' | 'string' | 'component';
  content: string | TemplateRef<any> | Type<any>;
  context;

  get title() {
    return navigator.onLine ? this.ref?.title : 'Sie sind offline, keine Verbindung zum Netzwerk';
  }

  constructor(public ref: UiModalRef) {}

  close(): void {
    this.ref.close(null);
  }

  ngOnInit(): void {
    this.content = this.ref.content;

    if (typeof this.content === 'string') {
      this.contentType = 'string';
    } else if (this.content instanceof TemplateRef) {
      this.contentType = 'template';
      this.context = {
        close: this.ref.close.bind(this.ref),
      };
    } else {
      this.contentType = 'component';
    }
  }
}
