import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Myorder } from './services/myorder';
import { ServiceService } from './../config/service.service';
import * as firebase from 'firebase';

@Injectable({
  providedIn: 'root'
})
export class MyordersService {
  product: Myorder[] = [];
  custId: string;
  orders: Myorder[];
  selItem: Myorder;

  constructor(
    public afs: AngularFirestore,
    public service: ServiceService
  ) {
    const users = this.service.get('user').then((data) => {
      if (data) {
        data = JSON.parse(data);
        this.custId = data.uid;
        if (this.custId !== undefined) {
          this.orderList(this.custId);
        }
      } else {
        this.custId = 'WwHnLICVY2dvZGUHuKqasiTB91a2';
      }
    });
  }

  public async orderList(custId) {
    console.log('called');
    console.log(custId);
    const This = this;
    const orderRef: AngularFirestoreCollection<any> = this.afs.collection('orders', ref => ref.where('custId', '==', custId)
    .orderBy('bookDate', 'desc'));
    orderRef.valueChanges().subscribe((value) => {
      console.log(value);
      this.orders = [];
      const res = value;
      if (res.length > 0) {
        res.forEach((item) => {
          console.log(item);
          const order: Myorder = {
            prodName: item.prodName,
            color: item.color,
            image: item.image,
            amount: item.amount,
            qty: item.qty,
            status: item.status,
            orderStatus: item.orderStatus,
            bookDate: item.bookDate,
            deliveryLocation: item.deliveryLocation,
            pickupLocation: item.pickupLocation,
            riderName: 'John',
            size: item.size,
            time: '60'
          };
          this.orders.push(order);
        });
        console.log(this.orders);
      } else {
        alert('No Orders Found');
      }
    });
  }

  public async trackOrder(order) {
      this.selItem = order;
  }

}
