import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { Authentication } from '../../../../services/Authentication';
import { Product } from 'app/models/Product';

@Component({
  selector: 'item-new',
  templateUrl: './new.component.html',
  imports: [ FormsModule, CommonModule ]
})
export class NewItemComponent {

  readonly maxFileMB = 16;

  newItem: Product = new Product();
  errorMsgs: string[] = [];

  constructor( private http: HttpClient, private router: Router, private route: ActivatedRoute, private title: Title, public auth: Authentication ) {
    this.title.setTitle("New | ADMIN");

    // If user is not logged in -> route home
    if (!auth.isLoggedIn){
      router.navigate(["/"]);
    }

    // If user is not Admin -> route home
    if (auth.loggedInUser.siteData.role != "Admin"){
      router.navigate(["/"]);
    }
  };

  sleep(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  selectedFiles: File[] = [];
  imagePreviews: string[] = [];
  onFileSelected(event: Event){
    const fileInput = event.target as HTMLInputElement;
    this.imagePreviews = [];
    this.selectedFiles = [];

    if (!fileInput.files?.length){
      return;
    }

    for (let i=0; i<fileInput.files.length; i++){
      let file = fileInput.files[i];
      if (file.size > this.maxFileMB * 1024 * 1024){
        this.errorMsgs.push("File exceeds max file size of 16MB");
        continue;
      }
      // No issues add file to the list
      this.selectedFiles.push( file );

      const reader = new FileReader();
      reader.onload= () => {
        this.imagePreviews.push(reader.result as string);
      }
      reader.readAsDataURL(file);
    }
  }

  onSubmit(){

    const formData = new FormData();

    // Append non-file fields
    formData.append("Name", this.newItem.name);
    formData.append("Description", this.newItem.description);
    formData.append("Cost", this.newItem.cost.toString());
    formData.append("Url", this.newItem.url);

    // Add image fileds
    if (this.selectedFiles.length > 0){
      for(let i=0; i<this.selectedFiles.length; i++){
        formData.append("images", this.selectedFiles[i], this.selectedFiles[i].name);
      };
    }

    // Proccess data
    this.http.post<boolean>( "api/product/create", formData ).subscribe({
        next: async (data) => {
            if (data == true){
              this.errorMsgs = ["Product Created Successfully"];
              await this.sleep(3000);
              this.router.navigate(["store/catalog"]);
            }else{
              this.errorMsgs = ["Error has ocurred"];
            }
        },
        error: err => {
            console.log("New Product Err: ", err);
        }
    });
  }
}