import {
  Component,
  ElementRef,
  EventEmitter,
  Input,
  Output,
  ViewChild,
} from '@angular/core';
import { v4 as uuid } from 'uuid';

@Component({
  selector: 'app-upload-recipe-picture',
  templateUrl: './upload-recipe-picture.component.html',
  styleUrls: ['./upload-recipe-picture.component.scss'],
})
export class UploadRecipePictureComponent {
  @Input() preview: string | null = null;
  @Input() isOptional = false;

  @Output() imageChange = new EventEmitter<string | null>();
  @Output() onUpload = new EventEmitter<File>();

  @ViewChild('inputFile') inputFile!: ElementRef<HTMLInputElement>;

  id = uuid();

  createPreviewUrl(file: File) {
    return URL.createObjectURL(file);
  }

  setPreview(file: File) {
    this.preview = this.createPreviewUrl(file);
    this.imageChange.emit(this.preview);
  }

  onUploadClick() {
    if (!this.inputFile?.nativeElement) return;

    this.inputFile.nativeElement.click();
  }

  handleUploadImage(event: Event) {
    const input = event.target as HTMLInputElement;
    const file = input.files?.[0];

    if (!file) return;

    this.onUpload.emit(file);

    this.preview = this.createPreviewUrl(file);
    this.imageChange.emit(this.preview);
  }
}
