import {
  Directive,
  ElementRef,
  EventEmitter,
  Output,
  Input,
  AfterViewInit,
  OnInit
} from '@angular/core';

import { NGXLogger } from 'ngx-logger';

@Directive({
  selector: 'img[ucapImage]'
})
export class ImageDirective implements OnInit, AfterViewInit {
  @Input()
  base: string;

  @Input()
  path: string;

  @Input()
  validation = true;

  @Input()
  default: string;

  @Output()
  loaded = new EventEmitter<HTMLImageElement>();

  imageSrc: string;

  constructor(
    private elementRef: ElementRef<HTMLImageElement>,
    private logger: NGXLogger
  ) {}

  ngOnInit(): void {
    if (this.validation) {
      if (
        !this.base ||
        '' === this.base.trim() ||
        !this.path ||
        '' === this.path.trim()
      ) {
        this.imageSrc = this.default;
      }
    }
  }

  ngAfterViewInit(): void {
    if (this.imageSrc === this.default) {
      this.elementRef.nativeElement.src = this.default;
      this.loaded.emit(this.elementRef.nativeElement);
    } else {
      this.elementRef.nativeElement.src = this.default;

      const imageUrl = `${this.base}${this.path}`;
      const image = new Image();
      image.onload = () => {
        if ('naturalHeight' in image) {
          if (image.naturalHeight + image.naturalWidth === 0) {
            image.onerror('naturalHeight');
            return;
          }
        }
        if (image.width + image.height === 0) {
          image.onerror('width');
          return;
        }
        this.elementRef.nativeElement.src = image.src;
        this.loaded.emit(image);
      };
      image.onerror = () => {
        this.elementRef.nativeElement.src = this.default;
        this.loaded.emit(this.elementRef.nativeElement);
      };
      image.src = imageUrl;
    }
  }
}
