import {AfterViewInit, Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {PageEvent} from '@angular/material/paginator';
import {ImageMetadata} from '../../interfaces/interface';
import {RestService} from '../../services/rest.service';
import {NGXLogger} from 'ngx-logger';
import {MatSnackBar} from '@angular/material/snack-bar';

@Component({
  selector: 'app-images',
  templateUrl: './images.component.html',
  styleUrls: ['./images.component.css']
})
export class ImagesComponent implements OnInit, AfterViewInit {

  @Input()
  images: ImageMetadata[];
  @Output()
  reload: EventEmitter<void> = new EventEmitter<void>();

  pageSizeOptions: number[] = [5, 10, 25, 100];
  lastPageEvent: PageEvent;

  constructor(
    public restService: RestService,
    private logger: NGXLogger,
    private snackbar: MatSnackBar
  ) {
  }

  ngOnInit(): void {
    this.lastPageEvent = {pageIndex: 0, pageSize: this.pageSizeOptions[0], length: this.images.length};
  }

  ngAfterViewInit(): void {

  }

  paginationGetStart(): number {
    return this.lastPageEvent.pageIndex * this.lastPageEvent.pageSize;
  }

  paginationGetEnd(): number {
    return this.paginationGetStart() + this.lastPageEvent.pageSize;
  }

  deleteImage(image: ImageMetadata) {
    this.restService.deleteImage(image.filename.split('.')[0]).toPromise().then(() => {
      this.snackbar.open('Successfully deleted ' + image.filename, 'Dismiss');
      this.reload.emit();
    }).catch(err => this.logger.error(err));
  }

  loadImage(i: number, id: string): void {
    this.restService.getImage(id).toPromise().then(image => {
      this.images[i].image_b64 = 'data:image/jpg;base64,' + image.image_data;
      this.logger.debug('image_b64', i, id, this.images[i].image_b64);
    }).catch(err => {
      this.logger.error('loadImage', i, id, err);
    });
  }

  filterOnlyNewestImageVersion() {
    return this.images.filter(image => !image.previous);
  }

  getImageIndex(image: ImageMetadata) {
    return this.images.findIndex(img => image === img);
  }

  getRelatedImageMeta(image: ImageMetadata, images: ImageMetadata[] = []) {
    const found = this.images.find(im => im.previous === image.identifier);
    if (found) {
      return this.getRelatedImageMeta(found, images.concat(found));
    } else {
      return images;
    }
  }
}
