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";
import { take } from "rxjs/operators";
import { Observable, of } from "rxjs";

@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);
          // this.orderState();
        }
      } else {
        this.custId = "WwHnLICVY2dvZGUHuKqasiTB91a2";
      }
    });
  }

  /*public async orgorderList(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.stateChanges().subscribe((value) => {
      // console.log(value[0].payload.doc.data());

    });
    orderRef.valueChanges().pipe(take(1)).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',
            orderId: item.orderId,
            size: item.size,
            orderCode: item.orderCode,
            product: this.service.key2Array(item.product),
            time: '60'
          };
          this.orders.push(order);
        });
        // console.log(this.orders);
      } else {
        alert('No Orders Found');
      }
      this.orderState();
    });
  }*/

  public async orderList(custId) {
    // console.log('called');
    // console.log(custId);
    const This = this;
    this.orders = [];
    const orderRef: AngularFirestoreCollection<any> = this.afs.collection(
      "orders",
      ref => ref.where("custId", "==", custId).orderBy("bookDate", "desc")
    );
    orderRef.stateChanges().subscribe(value => {
      // console.log(value);
      const res = value;
      // console.log(res);
      if (res.length > 0) {
        res.forEach(items => {
          const item = items.payload.doc.data();
          // console.log(item);
          const orderId = item.orderId;
          const order: Myorder = {
            amount: item.amount,
            status: item.status,
            orderStatus: item.orderStatus,
            bookDate: item.bookDate,
            deliveryLocation: item.deliveryLocation,
            pickupLocation: item.pickupLocation,
            deliveryAddress: item.deliveryAddress,
            riderName: "John",
            orderId: item.orderId,
            orderCode: item.orderCode,
            product: this.service.key2Array(item.product),
            time: "60"
          };
          // console.log(order);
          if (items.type === "added") {
            this.orders.push(order);
          } else {
            // console.log(orderId);
            const index = this.orders.findIndex(obj => obj.orderId === orderId);
            if (index >= 0) {
              this.orders[index] = order;
            }
          }
        });
        // console.log(this.orders);
      }
    });
  }

  /*  public orderState(): Observable<Myorder[]> {
    // console.log('called');
    const custId = 'WwHnLICVY2dvZGUHuKqasiTB91a2';
    this.orders = [];
    firebase.firestore().collection('orders').where('custId', '==', custId)
    .onSnapshot((snapData) => {
      snapData.docChanges().forEach((change) => {
        // console.log(change.type);
        if (change.type === 'modified') {
          const item = change.doc.data();
          // console.log(item);
          const orderId = item.orderId;
          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',
            orderId: item.orderId,
            size: item.size,
            time: '60'
          };
          const count = this.orders.length;
          for (let index = 0; index < count; index++) {
            if (this.orders[index].orderId === orderId) {
              // console.log(index);
              this.orders[index] = order;
              // console.log(this.orders);
              break;
            }
          }
        } else if (change.type === 'added') {
          const item = change.doc.data();
          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',
            orderId: item.orderId,
            size: item.size,
            time: '60'
          };
          this.orders.push(order);
        } else {
          //
        }
      });
    });

    /*



    .onSnapshot(function(snapshot) {
        snapshot.docChanges().forEach(function(change) {
            if (change.type === "added") {
                // console.log("New city: ", change.doc.data());
            }
            if (change.type === "modified") {
                // console.log("Modified city: ", change.doc.data());
            }
            if (change.type === "removed") {
                // console.log("Removed city: ", change.doc.data());
            }
        });
    });
    return of(this.orders);
  }
 */
  public async trackOrder(order) {
    this.selItem = order;
  }
}
