import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Products } from './services/product';
import { ServiceService } from './../config/service.service';

@Injectable({
  providedIn: 'root'
})
export class ProductsService {
  product: Products[] = [];
  selItem: Products;

  constructor(
    public afs: AngularFirestore,
    public service: ServiceService
  ) { }

  public async prodList() {
    const This = this;
    const prodRef: AngularFirestoreCollection<any> = this.afs.collection(`products`);
    prodRef.valueChanges().subscribe((value) => {
      this.product = [];
      const res = value;
      if (res.length > 0) {
        res.forEach((item) => {
          console.log(item.size);
          const prod: Products = {
            prodId: item.prodId,
            prodName: item.prodName,
            prodCode: item.prodCode,
            prodDesc: item.prodDesc,
            prodStatus: item.prodStatus,
            brand: item.brand.brandName,
            category: item.category.catName,
            color: item.color,
            discount: item.discount,
            featured: item.featured,
            image: item.image,
            price: item.price,
            qty: item.qty,
            shopper: item.shopper,
            skuCode: item.skuCode,
            status: item.status,
            size: this.service.key2Array(item.size),
            currency: item.currency
          };
          this.product.push(prod);
        });
        console.log(this.product);
      } else {
        alert('No Products Found');
      }
    });
  }

  public async setProd(item: Products) {
    this.selItem = item;
  }

}
