import { Injectable } from "@angular/core";
import {
  AngularFirestore,
  AngularFirestoreDocument,
  AngularFirestoreCollection
} from "@angular/fire/firestore";
import { Category } from "./services/category";
import * as firebase from "firebase";
import { ServiceService } from "./service.service";

@Injectable({
  providedIn: "root"
})
export class CategoriesService {
  categories: Category[] = [];
  activecategories: Category[] = [];
  constructor(public afs: AngularFirestore, public service: ServiceService) {
    this.categoryList();
    this.activeCategory();
  }

  public async categoryList() {
    const This = this;
    const orderRef: AngularFirestoreCollection<any> = this.afs.collection(
      "shopcategory"
    );
    orderRef.valueChanges().subscribe(value => {
      this.categories = [];
      const res = value;
      if (res.length > 0) {
        res.forEach(item => {
          // console.log(item);
          const category: Category = {
            catId: item.catId,
            catName: item.catName,
            catImage: item.catImage,
            featured: item.featured,
            status: item.status
          };
          this.categories.push(category);
        });
        // console.log(this.categories);
      } else {
        // alert('No Orders Found');
      }
    });
  }

  public async activeCategory() {
    const This = this;
    const state = true;
    const orderRef: AngularFirestoreCollection<any> = this.afs.collection(
      "shopcategory",
      ref => ref.where("status", "==", state)
    );
    orderRef.valueChanges().subscribe(value => {
      this.activecategories = [];
      const res = value;
      if (res.length > 0) {
        res.forEach(item => {
          // console.log(item);
          const category: Category = {
            catId: item.catId,
            catName: item.catName,
            catImage: item.catImage,
            featured: item.featured,
            status: item.status
          };
          this.activecategories.push(category);
        });
        // console.log(this.activecategories);
      } else {
        // alert('No Orders Found');
      }
    });
  }
}
