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';
import { resolve } from 'url';

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

  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 cancelOrder(orderId) {
    // tslint:disable-next-line:no-shadowed-variable
    const promise = new Promise(resolve => {
      this.afs
        .collection('orders')
        .doc(orderId)
        .update({
          orderStatus: 4,
          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 => {
      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,
            center: item.center,
            contactLess: item.contactLess,
            contactNo: item.contactNo,
            custExp: item.custExp,
            deliveredTime: item.deliveredTime,
            deliveryAddress: item.deliveryAddress,
            deliveryCharge: item.deliveryCharge,
            deliveryLocation: item.deliveryLocation,
            discount: item.discount,
            orderCode: item.orderCode,
            orderDate: item.orderDate,
            orderId: item.orderId,
            orderStatus: item.orderStatus,
            paymentMethod: item.paymentMethod,
            pickupAddress: item.pickupAddress,
            pickupLocation: item.pickupLocation,
            promoApplied: item.promoApplied,
            promoCode: item.promoCode,
            riderExp: item.riderExp,
            riderId: item.riderId,
            riderName: item.riderName,
            riderStatus: item.riderStatus,
            shopper: this.prodConfig(item.shopper),
            shoppers: item.shoppers,
            tax: item.tax,
            timeRemain: item.timeRemain,
            timeTaken: item.timeTaken,
            totalItem: item.totalItem,
            transId: item.transId,
            transaction: item.transaction
          };
          // 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 async getOrder(orderDta) {
    // tslint:disable-next-line:no-shadowed-variable
    const promise = new Promise((resolve) => {
      const orderRef: AngularFirestoreDocument<any> = this.afs.collection('orders').doc(orderDta.orderId);
      orderRef.valueChanges().subscribe(item => {
        console.log(item);
        const order: Myorder = {
          amount: item.amount,
          center: item.center,
          contactLess: item.contactLess,
          contactNo: item.contactNo,
          custExp: item.custExp,
          deliveredTime: item.deliveredTime,
          deliveryAddress: item.deliveryAddress,
          deliveryCharge: item.deliveryCharge,
          deliveryLocation: item.deliveryLocation,
          discount: item.discount,
          orderCode: item.orderCode,
          orderDate: item.orderDate,
          orderId: item.orderId,
          orderStatus: item.orderStatus,
          paymentMethod: item.paymentMethod,
          pickupAddress: item.pickupAddress,
          pickupLocation: item.pickupLocation,
          promoApplied: item.promoApplied,
          promoCode: item.promoCode,
          riderExp: item.riderExp,
          riderId: item.riderId,
          riderName: item.riderName,
          riderStatus: item.riderStatus,
          shopper: this.prodConfigShopper(item.shopper, orderDta.shopperId),
          shoppers: item.shoppers,
          tax: item.tax,
          timeRemain: item.timeRemain,
          timeTaken: item.timeTaken,
          totalItem: item.totalItem,
          transId: item.transId,
          transaction: item.transaction
        };
        this.selItem = order;
        const This = this;
        this.timeinterval = setInterval(() => {
          This.getDeliveryTime(this.selItem.orderDate.seconds, this.selItem.timeRemain);
        }, 1000);
        resolve(true);
      });
    });
    return promise;
  }

  getDeliveryTime(timeStamp, minute) {
    let endDate = new Date(timeStamp * 1000);
    endDate = new Date(endDate.getTime() + minute * 60000);

    if (Math.round(Date.now() / 1000) < Math.round(endDate.getTime() / 1000)) {
      // console.log(endDate);
      const t = this.getTimeRemaining(endDate, new Date());
      const minutes = t.minutes < 10 ? '0' + t.minutes : t.minutes;
      const seconds = t.seconds < 10 ? '0' + t.seconds : t.seconds;
      const hours = t.hours < 10 ? '0' + t.hours : t.hours;
      this.deliveryTime = t.hours + ' : ' + minutes + ' : ' + seconds;
      if (t.t <= 0) {
        clearInterval(this.timeinterval);
      }
    }

  }

  getTimeRemaining(endtime, currDate) {
    const t = Date.parse(endtime) - Date.parse(currDate);
    this.cancelDelivery = t;
    const hours = Math.floor((((t / 1000) / 60) / 60) % 60);
    const seconds = Math.floor((t / 1000) % 60);
    const minutes = Math.floor((t / 1000 / 60) % 60);
    return {
      t,
      hours,
      minutes,
      seconds
    };
  }

  prodConfig(ShoppItems) {
    const shopperData = [];
    // tslint:disable-next-line:forin
    for (const i in ShoppItems) {
      const shopData = ShoppItems[i];
      const product = [];
      // tslint:disable-next-line: forin
      for (const j in shopData.product) {
        const prodData = shopData.product[j];
        product.push(prodData);
      }
      shopData.product = product;
      shopperData.push(shopData);
    }
    return shopperData;
  }

  prodConfigShopper(ShoppItems, shopperId) {
    const shopData = ShoppItems[shopperId];
    const product = [];
      // tslint:disable-next-line: forin
    for (const j in shopData.product) {
        const prodData = shopData.product[j];
        product.push(prodData);
      }
    shopData.product = product;
    return shopData;
  }

  /*  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;
  }
}
