import { HttpClient, HttpEvent, HttpEventType } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { catchError, Observable } from 'rxjs';
import { ConfigService } from '../config.service';
import { CookiesService } from '../cookies.service';

@Component({
  selector: 'app-uploads',
  templateUrl: './uploads.component.html',
  styleUrls: ['./uploads.component.css']
})
export class UploadsComponent implements OnInit {
  public vidName: any;
  public vidFile: File;
  public vidThumbnail: File;
  public progress: number = 0;
  public status: string = "idle";
  constructor(
    private http: HttpClient, 
    private config: ConfigService,
    private cookies: CookiesService) { }

  ngOnInit(): void {
  }

  onSubmit():void {
    const userCookie = this.cookies.getCookie('proxima-login-cookie');
    const formData = new FormData();
    formData.append("title", this.vidName);
    formData.append("file", this.vidFile);
    formData.append("thumbnail", this.vidThumbnail);
    formData.append("creator", this.cookies.getCookie('proxima-login-cookie').split(',')[2])
    
    console.log("sending Data")

    this.http.post<any>(this.config.hostname + '/videos/upload', formData, {
      reportProgress: true,
      observe: 'events',
    }).subscribe((event: HttpEvent<any>) => {
      switch (event.type) {
        case HttpEventType.Sent:
          console.log('Request has been made!');
          break;
        case HttpEventType.ResponseHeader:
          console.log('Response header has been received!');
          break;
        case HttpEventType.UploadProgress:
          var eventTotal = event.total ? event.total : 0;
          this.progress = Math.round(event.loaded / eventTotal * 100);
          this.status = `Uploaded! ${this.progress}%`;
          console.log(`Uploaded! ${this.progress}%`);
          break;
        case HttpEventType.Response:
          console.log('Video Upload Successfully!', event.body);
          this.status = 'Video Upload Successfully!';
          setTimeout(() => {
            this.progress = 0;
            this.status = "idle";
          }, 1500);
          break;
      }
    });
  }
  onFileSelected(event):void {
    this.vidFile = event.target.files[0];
  }

}
