// Angular Core
import { Component, ElementRef, Input, OnInit, Renderer2, ViewChild } from '@angular/core';

// Services
import { SessionService } from 'src/app/services/session/session.service';

// Third Party
import { NgbModal, NgbModalConfig } from '@ng-bootstrap/ng-bootstrap';
import { environment } from 'src/environments/environment';

@Component({
  standalone: false,
  selector: 'app-product-image',
  templateUrl: './product-image.component.html',
  styleUrls: ['./product-image.component.scss']
})
export class ProductImageComponent implements OnInit {

  @Input() images!: Array<string>;
  @ViewChild('imageModal') imageModal!: ElementRef;

  cdnLink!: string;
  imgPath!: string;
  //image path for local images
  imgUrl: string = environment.imageUrl;
  /**
   * define fall back path if image doesnt exist
   */
  urlProdfallback = this.imgUrl+'/ICON-No-Image.png';
  urlThumbfallback = this.imgUrl+'/ICON-No-Image.png';//left in case we ever need to use a diff fall back thumb image
  urlThumb!:string;
  mainImage!:string;

  constructor(
    private sessionService: SessionService,
    private renderer: Renderer2,
    private modalService: NgbModal,
    private elRef: ElementRef,
    private ngbModalconfig: NgbModalConfig,
  ) { 
    // customize default values of modals used by this component tree
		this.ngbModalconfig.backdrop = 'static';
		this.ngbModalconfig.keyboard = false;
  }

  ngOnInit(): void {
    this.cdnLink = this.sessionService.getSession().cdnUrl;
    this.imgPath = "//" + this.sessionService.getSession().cdnUrl + "/images";
    if (location.href.indexOf("trxade.com") !== -1) {
      this.imgPath = "//" + this.cdnLink + "/pimg";
    }    

    /**
     * initialize variables based on passed scope vars
     */
    if(this.images[0] === '' || typeof this.images[0] === 'undefined') {
      this.mainImage =  this.urlProdfallback;
      this.urlThumb = this.urlThumbfallback;
    } else {
        this.mainImage = this.images[0];
        this.urlThumb = this.imgPath + '/product/thumbs/' + this.images[0];
    }

    /**
     * Onload, check if the image exists if not then load fallback image for thumb picture
     */
    this.isImage(this.urlThumb).then((result) => {
      if(!result) {
          this.urlThumb = this.urlThumbfallback;
      }
      this.setPicThumb(this.urlThumb);
    });
  }

  /**
   * checks if the sent src path exists
   * @param {string} src
   * @returns {$q@call;defer.promise}
   */
  isImage(src:string) {
    return new Promise((resolve, reject) => {
      const image = new Image();
      image.onerror = () => resolve(false);
      image.onload = () => resolve(true);
      image.src = src;
    });
  };

  /**
   * Sets pic thumb css and url location of the image
   * @param {string} myurl
   * @returns {undefined}
   */                
  setPicThumb(myurl:string) {
    const productthumbImage = this.elRef.nativeElement.querySelector('.product-thumb');
    this.renderer.setStyle(productthumbImage, 'background-image', 'url(' + myurl + ')');
    this.renderer.setStyle(productthumbImage, 'background-size', '100% 100%');
    this.renderer.setStyle(productthumbImage, 'background-repeat', 'no-repeat');
    this.renderer.setStyle(productthumbImage, 'width', '30px');
    this.renderer.setStyle(productthumbImage, 'height', '30px');
    this.renderer.setStyle(productthumbImage, 'top', '-22%');
  };

  /**
  * Private property to set the status of Image Modal
  * @type boolean
  */
  ImageOpened:boolean = false;

  /**
   * Private property to store base-modal config
   * @type Object
   */
  ImageModalConfig:any = {
      showHeader: true,
      title: 'Product Images'
  };
  ImageModal!:any;
  /**
  * Private method to show the OutOfStockPopup modal
  * @returns null
  */
  showImageModal() {
    this.ImageModal = this.modalService.open(this.imageModal, {size: 'sm'})

    this.ImageModal.shown.subscribe(() => {
      this.ImageOpened = true;
    })

    this.ImageModal.closed.subscribe(() => {
      this.ImageOpened = false;
    })
  };

  clickPic(){
    if(this.urlThumb !== this.urlThumbfallback) {
        //only load picture if there is an existing one
        this.showImageModal();
    }
  };

  /**
   * Change image on modal when an image is selected from the
   * given product image list in the modal.
   * @param {string} image
   * @returns {undefined}
   */
  changeImage (image: string) {
    this.mainImage = image;
  };

  closeModal(){
    this.ImageModal.close();
  }

}
