import { Component, HostListener } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { LogoOptions, MovieLogos } from './movie.enum';
import { FormControl } from "@angular/forms";

@Component({
  selector: 'app-movie',
  templateUrl: './movie.component.html',
})
export class MovieComponent {
  selectedFile: File | null = null;
  retrievedImage: any;
  base64Data: any;
  retrieveResponse: any;
  message: string | undefined;
  windowHeight: number = window.innerHeight - 200;
  topSubtitle: any;
  title: any;
  title2: any;
  subtitle: any;
  index: any;
  movieLogos = MovieLogos;
  logoOptions = LogoOptions
  selectedLogoControl = new FormControl();
  logoOptionControl = new FormControl();
  imageTitle = 'poster'

  constructor(private http: HttpClient)
  {
    this.onResize();
  }

  onFileSelected(event: Event) {
    const element = event.target as HTMLInputElement;
    let files = element.files;
    this.selectedFile = files && files.length > 0 ? files[0] : null;
  }

  onUpload() {
    if (!this.selectedFile) {
      console.log('No file selected');
      return;
    }
    const fd = new FormData();
    fd.append('image', this.selectedFile, this.selectedFile.name);
    fd.append('topSubtitle', this.topSubtitle);
    fd.append('title', this.title);
    fd.append('subtitle', this.subtitle);
    fd.append('index', this.index);
    fd.append('title2', this.title2);
    if (this.selectedLogoControl.value != null){
      fd.append('logo', this.selectedLogoControl.value);
    }
    if (this.logoOptionControl.value != null) {
      fd.append('logoOption', this.logoOptionControl.value);
    }

    this.http.post('http://localhost:44369/poster/movie', fd)
      .subscribe(res => {
        console.log(res);
        this.retrieveResponse = res;
        this.base64Data = this.retrieveResponse.picBytes;
        this.retrievedImage = 'data:image/jpeg;base64,' + this.base64Data;
      });
  }

  downloadImage(): void {
    if (this.retrievedImage) {
      const link = document.createElement('a');
      link.href = this.retrievedImage;
      link.download = `${this.imageTitle}.jpeg`; // Specify the filename here
      link.click();
    }
  }

  @HostListener('window:resize')
  onResize() {
    this.windowHeight = window.innerHeight - 200;
  }
}
