import {Component, ElementRef, HostListener, OnDestroy, ViewChild} from '@angular/core';
import {RouterLink} from '@angular/router';
import {CanComponentDeactivate} from './pending.guard';
import {NgIf} from '@angular/common';
import {PictureService} from '../gallery/picture.service';

@Component({
  selector: 'app-upload',
  imports: [
    RouterLink,
    NgIf
  ],
  templateUrl: './upload.component.html',
  styleUrl: './upload.component.less'
})
export class UploadComponent implements OnDestroy, CanComponentDeactivate {

  @ViewChild('preview')
  protected preview!: ElementRef;

  @ViewChild('input')
  protected input!: ElementRef;

  protected selected: File | null = null;

  protected uploading: boolean = false;

  protected success: boolean | null = null;

  constructor(
    protected imageService: PictureService,
  ) {
    //
  }

  fileChanged() {
    this.reset(null);
    const file = this.input.nativeElement.files?.[0];
    if (file && file.type.startsWith('image/')) {
      const reader = new FileReader();
      reader.onload = readerEvent => {
        this.preview.nativeElement.src = (readerEvent.target?.result || '') as string;
        this.selected = file;
      };
      reader.readAsDataURL(file);
    }
  }

  private reset(success: boolean | null) {
    this.uploading = false;
    this.success = success;
    if (success !== false) {
      this.selected = null;
      this.preview.nativeElement.src = 'placeholder.svg';
    }
  }

  @HostListener('window:beforeunload', ['$event'])
  unloadNotification($event: BeforeUnloadEvent): void {
    if (this.selected) {
      $event.preventDefault();
    }
  }

  canDeactivate(): boolean {
    if (this.selected) {
      return confirm('Du hast ein Foto ausgewählt, aber noch nicht hochgeladen. Wirklich verlassen?');
    }
    return true;
  }

  ngOnDestroy(): void {
    window.removeEventListener('beforeunload', this.unloadNotification);
  }

  upload() {
    if (this.uploading) {
      return;
    }
    if (!this.selected) {
      return;
    }
    this.uploading = true;
    this.imageService.upload(this.selected, () => this.reset(true), () => this.reset(false));
  }

}
