import { Injectable } from '@angular/core';
import {
  AngularFirestore,
  AngularFirestoreDocument
} from '@angular/fire/firestore';
import { Router } from '@angular/router';
import { ServiceService } from './service.service';
import { CartsService } from './cart.service';
import { Products } from './services/product';
import { User } from './services/user';
import { take } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class WishService {
  wish: Products;
  user: User;
  whishItem: Products[] = [];
  wishItems: any;
  constructor(
    public afs: AngularFirestore,
    public router: Router,
    public service: ServiceService,
    public cartService: CartsService
  ) {
    this.whishItem = [];
  }

  public async wishList(custId) {
    console.log(custId);
    const cartRef: AngularFirestoreDocument<any> = this.afs
      .collection('favourite')
      .doc(custId);
    this.whishItem = [];
    cartRef.valueChanges().subscribe(value => {
      this.whishItem = [];
      console.log(value);
      this.wishItems = value;
      /* value = this.service.key2Array(value);
      console.log(value); */
      // tslint:disable-next-line:forin
      for (const i in value) {
        const prodRef: AngularFirestoreDocument<any> = this.afs
          .collection('products')
          .doc(i);
        prodRef
          .valueChanges()
          .pipe(
            take(1) // Here you can limit to only emit once, using the take operator
          )
          .subscribe(prodValue => {
            console.log(prodValue);
            if (prodValue) {
              const item = prodValue;
              const wishItem: Products = {
                color: this.service.splitSep(item.color),
                shopperId: item.shopperId,
                shopper: item.shopper,
                prodId: item.prodId,
                price: item.price,
                prodName: item.prodName,
                image: item.image,
                qty: 1,
                brand: item.brand,
                category: item.category,
                discount: item.discount,
                featured: item.featured,
                prodCode: item.prodCode,
                prodDesc: item.prodDesc,
                prodStatus: item.prodStatus,
                rating: item.rating,
                skuCode: item.skuCode,
                status: item.status,
                subCate: item.subCate,
                tag: this.service.splitSep(item.tag),
                size: this.service.splitSep(item.size)
              };
              const found = this.whishItem.some(
                el => el.prodId === item.prodId
              );
              if (!found) {
                this.whishItem.push(wishItem);
              }
              console.log(this.whishItem);
            } else {
              // alert('No Products Found');
            }
          });
      }
    });
  }

  clearWish(custId) {
    const promise = new Promise(resolve => {
      this.afs
        .collection('favourite')
        .doc(custId)
        .delete();
      resolve(true);
    });
    return promise;
  }

  clearWishItem(custId, prodId) {
    delete this.wishItems[prodId];
    console.log(custId, prodId);
    const promise = new Promise(resolve => {
      this.afs
        .collection('favourite')
        .doc(custId)
        .set(this.wishItems);
      resolve(true);
    }).catch(err => {
      console.log(err);
    });
    return promise;
  }

  addToCart(custId, items) {
    const promise = new Promise(resolve => {
      items.forEach(item => {
        this.cartService.buyNow(item);
      });
      resolve(true);
    });
    return promise;
  }
}
