import {
  Injectable,
  ComponentFactoryResolver,
  ApplicationRef,
  Injector,
  EmbeddedViewRef,
  ComponentRef,
  Input,
  Type
} from '@angular/core';
import { DescriptiveCardComponent } from './descriptive-card.component';
import { DescriptiveCardCSSProperties } from '../../interfaces/descriptive-card-css-properties-interface';
import { Subject, Observable } from 'rxjs';

@Injectable()
export class DescriptiveCardService {
  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private applicationRef: ApplicationRef,
    private injector: Injector
  ) { }

  // private dcpSubject = new Subject<DescriptiveCardProperties>();
  private dcspSubject = new Subject<DescriptiveCardCSSProperties>();

  private componentRef: ComponentRef<DescriptiveCardComponent> = null;

  setDcsp(dcsp: DescriptiveCardCSSProperties) {
    this.dcspSubject.next(dcsp);
  }

  clearDcsp() {
    this.dcspSubject.next();
  }

  getDcsp(): Observable<DescriptiveCardCSSProperties> {
    return this.dcspSubject.asObservable();
  }

  appendComponentToBody(): ComponentRef<DescriptiveCardComponent> {
    if (this.componentRef === null) {
      this.componentRef = this.componentFactoryResolver.resolveComponentFactory(DescriptiveCardComponent).create(this.injector);

      this.applicationRef.attachView(this.componentRef.hostView);

      const domElem = (this.componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;

      document.body.appendChild(domElem);
      return this.componentRef;
    }
    return this.componentRef;
  }

  removeComponentFromBody() {
   

  if(this.componentRef !==null){
   this.clearDcsp();
    this.applicationRef.detachView(this.componentRef.hostView);
    this.componentRef.destroy();
    this.componentRef = null;
    }
  }
}
