import { Component, NgZone } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { FormsModule, NgModel } from '@angular/forms';
import { Router, ActivatedRoute, RouterModule } 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: 'store-catalog',
  templateUrl: './catalog.component.html',
  styleUrl: './catalog.component.css',
  imports: [ FormsModule, CommonModule, RouterModule ]
})
export class CatalogComponent {

  public Products: Product[] = [];

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

    // load each product
    http.post<Product[]>("api/product/getall", null).subscribe(
      response => {
        this.Products = response;

        // Load each image
        this.Products.forEach(item => {
          item.curShowingIMG = 0;
          item.images.forEach(img => {
            http.get("api/productimage/get?ProductID=" + img.productID + "&ImageID=" + img.imageID, { responseType: 'blob' }).subscribe(blob => {
              img.imageSrc = URL.createObjectURL(blob);
              console.log(img.imageSrc);
            });
          });
        });

      }
    )
  };

  nextImg( prod: Product ){
    prod.curShowingIMG += 1;
    if (prod.curShowingIMG == prod.images.length){
      prod.curShowingIMG = 0;
    }
  }

  prevImg( prod: Product ){
    prod.curShowingIMG -= 1;
    if (prod.curShowingIMG == -1){
      prod.curShowingIMG = prod.images.length -1;
    }
  }

  DeleteItem( ProductID: number ) {
    const body = new HttpParams()
        .set("productID", ProductID);
    const headers = new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded',
    });
    this.http.post<boolean>( "api/product/delete", body, { headers } ).subscribe({
      next: data => {
        if (data){
          window.location.reload();
        }
      }
    })
  }
}