import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {Router} from '@angular/router';
import {ImagePopupDialogComponent} from '../image-popup-dialog/image-popup-dialog.component';
import {AuthService} from '../service/auth.service';
import {UploadMetaModel} from '../models/uploadMetaModel';
import {UploadAttachService} from '../service/upload.attach.service';
import {AppConfig} from '../app.config';



@Component({
  selector: 'app-upload-cards',
  templateUrl: './upload-cards.component.html',
  styleUrls: ['./upload-cards.component.scss']
})
export class UploadCardsComponent implements OnInit {
  @Input() uploadId: number;
  @Input() icon  = '';
  @Output() deleted = new EventEmitter<UploadMetaModel>();
  @ViewChild('imgBox', {static: true}) imgBox: ImagePopupDialogComponent;
  @ViewChild('downloadLink', {static: true}) downloadLink: ElementRef<HTMLAnchorElement>;
  public uploadMeta: UploadMetaModel = new UploadMetaModel({});

  public thumbImage = '';
  public fullImage = '';

  public IsNew = false;

  constructor(private router: Router, private auth: AuthService, private uas: UploadAttachService, private config: AppConfig) {
    this.thumbImage = location.origin + '/assets/img/nopreview-thumb.png';
  }

  ngOnInit(): void {
    let url = this.auth.getUrl('upload-as-thumbnail/' + this.uploadId);
    this.thumbImage = url ;
    url = this.auth.getUrl('upload-as-image/' + this.uploadId);
    this.fullImage = url;

    this.uas.getUploadMeta(this.uploadId).subscribe( resp => {
      this.uploadMeta = new UploadMetaModel(resp);
      this.icon = this.uploadMeta.iconUrl;
      this.IsNew = this.DateDiff(this.uploadMeta.Ts, new Date()) < 1;
    });
  }


  private DateDiff(date1: Date, date2: Date): number {
    const dt1 = new Date(date1);
    const dt2 = new Date(date2);
    return Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate())
      - Date.UTC(dt1.getFullYear(), dt1.getMonth(), dt1.getDate()) )
      / (1000 * 60 * 60 * 24));
  }

  public onNavigateTo(id: number ): void{
    this.router.navigate(['/upload-details/', id]);
  }

  public urlForDownload(id: number ): string{
    return this.uas.getUploadAsOriginalUrl(id);
  }

  public onDownload(id: number ): void{
    const el = this.downloadLink.nativeElement;
    el.href = this.urlForDownload(id);
    el.click();
  }

  public onSearch(id: number ): void{
    this.popupImage(this.fullImage);
    // this.popupImage(this.thumbImage);
  }

  public popupImage(url: string): void {
    this.imgBox.showImg(url, this.uploadId + ' - ' + this.uploadMeta.FileName);
  }

  public onDelete(id: number): void {
    this.uas.deleteUpload(id).subscribe( resp => {
      const ulMeta = new UploadMetaModel(resp);
      this.deleted.emit(ulMeta);
    });
  }
}
