import { Injectable } from '@angular/core';
import {
  AngularFirestore,
  AngularFirestoreDocument,
  AngularFirestoreCollection
} from '@angular/fire/firestore';
import { Router, ActivatedRoute } from '@angular/router';
import { Order, OrderData, Product, Shopper } from './services/order';
import { Products } from './services/product';
import { ServiceService } from './service.service';
import { SubjectService } from './subject.service';
import * as firebase from 'firebase';
import { CartItem } from './services/cart';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class OrdersService {
  order: Order;
  size: string;
  color: string;
  custId: string;
  shopperId: any;
  checkout = new BehaviorSubject(false);
  users: any;
  cartCount: any;
  email: any;
  displayName: string;
  phone: any;

  constructor(
    public afs: AngularFirestore,
    public router: Router,
    public service: ServiceService,
    public subject: SubjectService
  ) {
    this.size = 'small';
    this.color = 'Blue';
    this.custId = '';
    this.service.get('userData').then(data => {
      if (data) {
        data = JSON.parse(data);
        this.users = data;
        console.log(this.users);
        this.custId = data.uid;
        this.email = data.emailId;
        this.displayName = data.name;
        this.phone = data.phone;
        // console.log(this.custId);
      } else {
        this.custId = 'WwHnLICVY2dvZGUHuKqasiTB91a2';
      }
    });
  }

  /*public async orgcheckOut(cart: CartItem[]) {
    // console.log(cart);
    // console.log(this.users);
    return;
    let currProcess = 0;
    const cartCount = cart.length;
    cart.forEach((product) => {
      this.afs.collection('orders').add({
        bookDate: firebase.firestore.FieldValue.serverTimestamp()
      }).then((docRef) => {
        const neworderId = docRef.id;
        const delivery = new firebase.firestore.GeoPoint(10.0237, 76.3116);
        const pickup = new firebase.firestore.GeoPoint(10.7231, 76.1234);
        const orderItem: Order = {
          amount: 'A$ 175',
          customer: firebase.firestore().doc('/customer/' + this.custId),
          shopper: product.shopperId,
          deliveryAddress: 'Techware Software solution, Carnival Infopark, Kochi',
          deliveryCharge: 'A$ 0.5',
          deliveryLocation: delivery,
          bookDate: firebase.firestore.FieldValue.serverTimestamp(),
          discount: 'A$ 12.00',
          orderCode: this.orderCode(),
          orderId: neworderId,
          orderStatus: 1,
          pickupAddress: 'GetMi, Canberra, AUS',
          pickupLocation: pickup,
          price: 'A$ ' + product.price,
          product: firebase.firestore().doc('/product/' + product.prodId),
          promoId: null,
          qty: product.qty,
          rider: firebase.firestore().doc('/riders/qbTKza18mWVzYG9NLIbmjMbrYjG2'),
          status: 1,
          tax: 'A$ 7.5',
          size: product.size,
          color: product.color,
          custId: this.custId,
          image: product.image,
          prodId: product.prodId,
          prodName: product.prodName,
          riderId: 'qbTKza18mWVzYG9NLIbmjMbrYjG2',
          shopperId: 'qbTKza18mWVzYG9NLIbmjMbrYjG2'
        };
        this.afs.collection('orders').doc(neworderId).set(orderItem).then(() => {
          currProcess += 1;
          // console.log('Booking Successfully');
          this.afs.doc(`carts/${product.cartId}`).delete();
          // this.router.navigateByUrl('cart');
          // console.log(currProcess, cartCount);
          document.body.scrollTop = document.documentElement.scrollTop = 0;
          if (currProcess === cartCount) {
            // this.router.navigateByUrl('cart');
            return true;
          }
        });
      }).catch((error) => {
        console.error('Error adding document: ', error);
      });
    });

  }*/

  public async checkOut(cart: CartItem[], otherCharge, centerLoc: any) {
    console.log(cart, otherCharge, centerLoc);
    const cartGroup = [];
    const distinctShops = [];
    const map = new Map();
    for (const item of cart) {
      if (!map.has(item.shopperId)) {
        map.set(item.shopperId, true); // set any value to Map
        distinctShops.push(item.shopperId);
      }
    }


    cart.forEach(items => {
      cartGroup[items.shopperId] = cartGroup[items.shopperId] === undefined ? [] : cartGroup[items.shopperId];
      cartGroup[items.shopperId].push(items);
    });
    this.cartCount = distinctShops.length;
    const timer = ((this.cartCount - 1) * 20) + 60;
    const pickup = new firebase.firestore.GeoPoint(centerLoc.latLng.latitude, centerLoc.latLng.longitude);
    const promise = new Promise(async resolve => {
      const shopRef = await this.afs.collection(`shoppers`,
        ref =>
          ref
            .where('uid', 'in', distinctShops)
      );
      shopRef.valueChanges().subscribe((value: any) => {
        console.log(value);
        const shoppersData = value;
        console.log(shoppersData);
        const shoppers = {};
        distinctShops.forEach(item => {
          const shopperInfo = shoppersData.find((ret) => ret.uid === item);
          console.log(shopperInfo);
          const cartItem = cartGroup[item];
          shoppers[item] = {};
          const shopper: Shopper = {
            amount: 0,
            getmiCharge: 0,
            product: {},
            shopperEarn: 0,
            shopperId: shopperInfo.uid,
            shopperName: shopperInfo.shopName,
            shopperOrderNo: this.orderCode(),
            shopperRef: firebase.firestore().doc('/shoppers/' + shopperInfo.uid),
            shopperStatus: 0
          };
          const products = {};
          cartItem.forEach(prodItem => {
          shopper.amount += prodItem.price;
          const prod: Product = {
            prodId: prodItem.prodId,
            skuCode: prodItem.skuCode,
            prodName: prodItem.prodName,
            image: prodItem.image,
            price: prodItem.price,
            gst: prodItem.gst,
            color: prodItem.color,
            size: prodItem.size,
            qty: prodItem.qty,
            itemId: `${shopperInfo.uid}-${prodItem.skuCode}-${this.pad(Math.round(Math.random() * 1000), 3, null)}`,
            discount: 0
          };
          products[prodItem.prodId] = prod;
          this.afs.doc(`carts/${prodItem.cartId}`).delete();
        });
          shopper.product = products;
          shoppers[item] = shopper;
      });
        const orderItem: OrderData = {
          amount: otherCharge.totalAmt.toFixed(2),
          orderDate: firebase.firestore.FieldValue.serverTimestamp(),
          center: centerLoc,
          custId: this.custId.trim(),
          custName: this.displayName,
          deliveryAddress: otherCharge.custAddress,
          deliveryCharge: otherCharge.deliveryCharge.toFixed(2),
          deliveryLocation: otherCharge.custAddress.latLng,
          discount: otherCharge.discount.toFixed(2),
          email: this.email,
          orderCode: this.gmCode(),
          contactLess: otherCharge.contactLess,
          contactNo: this.phone,
          custExp: {
            rating: 0,
            feedback: ''
          },
          customer: firebase.firestore().doc('/customer/' + this.custId.trim()),
          deliveredTime: '',
          orderId: '',
          orderStatus: 1,
          paymentMethod: otherCharge.paymentMethod,
          pickupAddress: centerLoc.location,
          pickupLocation: pickup,
          promoApplied: otherCharge.discountApplied,
          promoCode: otherCharge.promoCode ? otherCharge.promoCode : '',
          promoId: otherCharge.promoId ? otherCharge.promoId : '',
          rider: '',
          riderExp: {
            rating: 0,
            feedback: ''
          },
          riderId: '',
          riderName: '',
          riderStatus: 0,
          shopper: shoppers,
          shoppers: distinctShops,
          tax: otherCharge.taxAmount.toFixed(2),
          timeRemain: timer,
          timeTaken: 0,
          totalItem: cart.length,
          transId: otherCharge.transId,
          transaction: otherCharge.transaction
        };

        this.afs.collection('orders')
          .add(orderItem)
          .then(docRef => {
            const neworderId = docRef.id;
            console.log(neworderId);
            this.afs
              .collection('orders')
              .doc(neworderId)
              .update({ orderId: neworderId })
              .then(() => {
                resolve('Cart to Order Successfully');
                document.body.scrollTop = document.documentElement.scrollTop = 0;
              });
          }).catch(error => {
            console.error('Error adding document: ', error);
          });
      });
    });
  }

  public async changeOrder(orderId, status) {
    // console.log(orderId, status);
    this.afs
      .collection('orders')
      .doc(orderId)
      .update({ orderStatus: status });
  }

  public async buyNow(product: Products) {
    //
  }

  orderCode() {
    const newpin = Math.round(Math.random() * 1000000);
    const orderCode = 'GM' + this.pad(newpin, 6, null);
    return orderCode;
  }

  gmCode() {
    const newpin = Math.round(Math.random() * 1000000);
    const orderCode = 'OD' + this.pad(newpin, 5, null) + new Date().valueOf();
    return orderCode;
  }

  pad(n, width, z) {
    z = z || '0';
    n = n + '';
    return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
  }

  choose_size(size: string) {
    this.size = size;
  }
}
