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 cancelOrder(orderId) {
    const promise = new Promise(resolve => {
      this.afs
        .collection('orders')
        .doc(orderId)
        .update({
          orderStatus: 0,
          cancelTime: firebase.firestore.FieldValue.serverTimestamp()
        });
      resolve(true);
    });
    return promise;
  }

  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('orderDate', '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,
            orderDate: item.orderDate,
            orderStatus: item.orderStatus,
            bookDate: item.bookDate,
            deliveryLocation: item.deliveryLocation,
            pickupLocation: item.pickupLocation,
            deliveryAddress: item.deliveryAddress,
            paymentMode: item.paymentMethod,
            riderName: 'John',
            orderId: item.orderId,
            orderCode: item.orderCode,
            product: this.service.key2Array(item.product),
            time: item.timeRemain
          };
          // 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;
            }
          }
        });
        this.orders.sort((a, b) => Number(b.orderDate) - Number(a.orderDate));
        // 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 getNearBy(latitude, longitude, orderId) {
    const promise = new Promise(resolve => {
      const This = this;

      const lat = 0.0144927536231884;
      const lon = 0.0181818181818182;
      const distance = this.service.distance;

      const lowerLat = latitude - lat * distance;
      const lowerLon = longitude - lon * distance;

      const greaterLat = latitude + lat * distance;
      const greaterLon = longitude + lon * distance;

      const lesserGeopoint = new firebase.firestore.GeoPoint(lowerLat, lowerLon);
      const greaterGeopoint = new firebase.firestore.GeoPoint(
        greaterLat,
        greaterLon
      );
      const addressRef: AngularFirestoreCollection<any> = this.afs.collection(
        'orders',
        ref =>
          ref
            .where('pickupLocation', '>', lesserGeopoint)
            .where('pickupLocation', '<', greaterGeopoint)
            .where('orderId', '==', orderId)
      );
      addressRef.valueChanges().subscribe(value => {
        const res = value;
        if (res.length > 0) {
          resolve(true);
        } else {
          resolve(false);
        }
      });
    });
    return promise;
  }

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