import { Directive, ElementRef, Input, OnChanges, OnDestroy, OnInit, Renderer2, SimpleChanges } from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';

@Directive({
  selector: '[bixiSafeSrc]',
  exportAs: 'bixiSafeSrc'
})
export class SafeSrcDirective implements OnInit, OnChanges, OnDestroy {
  src = '';
  @Input() bixiSafeSrc: string;
  @Input() bixiErrorClass = 'bixi-safe-src-error';
  @Input() bixiSuccessClass = 'bixi-safe-src-success';
  @Input() bixiErrorSrc: string;

  subscription = new Subscription();

  constructor(
    private el: ElementRef,
    private renderer: Renderer2
  ) {

  }

  ngOnInit() {
    this.setSrc(this.bixiSafeSrc);
    this.watchError();
  }

  ngOnChanges(changes: SimpleChanges) {
    const srcChange = changes.bixiSafeSrc;
    if (srcChange.firstChange) return;
    this.setSrc(this.bixiSafeSrc);
  }

  setSrc(src: string) {
    if (!src) return;
    if (this.src === src) return;
    this.src = src;
    this.renderer.setAttribute(this.el.nativeElement, 'src', src);
  }


  watchError() {
    this.subscription.add(fromEvent(this.el.nativeElement, 'error').subscribe(() => {
      this.setSrc(this.bixiErrorSrc);
      this.renderer.addClass(this.el.nativeElement, this.bixiErrorClass);
      this.renderer.removeClass(this.el.nativeElement, this.bixiSuccessClass);
    }));

    this.subscription.add(fromEvent(this.el.nativeElement, 'load').subscribe(() => {
      if (this.src === this.bixiErrorSrc) return;
      this.renderer.addClass(this.el.nativeElement, this.bixiSuccessClass);
      this.renderer.removeClass(this.el.nativeElement, this.bixiErrorClass);
    }));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

}
