import * as tslib_1 from "tslib";
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Router } from '@angular/router';
import { ServiceService } from './service.service';
import { SubjectService } from './subject.service';
import * as firebase from 'firebase';
import { BehaviorSubject } from 'rxjs';
let OrdersService = class OrdersService {
    constructor(afs, router, service, subject) {
        this.afs = afs;
        this.router = router;
        this.service = service;
        this.subject = subject;
        this.checkout = new BehaviorSubject(false);
        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;
                // 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);
        });
      });
  
    }*/
    checkOut(cart, otherCharge, centerLoc) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            // console.log(cart);
            // console.log(this.users);
            const cartGroup = [];
            // const distinctShops = [...new Set(cart.map(obj => obj.shopperId))];
            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;
            // console.log(cartGroup);
            // console.log(cartCount);
            const promise = new Promise(resolve => {
                distinctShops.forEach(item => {
                    const pickup = new firebase.firestore.GeoPoint(centerLoc.latLng.latitude, centerLoc.latLng.longitude);
                    const products = {};
                    const cartItem = cartGroup[item];
                    let prodPrice = 0;
                    cartItem.forEach(prodItem => {
                        prodPrice += prodItem.price;
                        products[prodItem.prodId] = {
                            prodId: prodItem.prodId,
                            prodName: prodItem.prodName,
                            image: prodItem.image,
                            price: prodItem.price,
                            color: prodItem.color,
                            size: prodItem.size,
                            qty: prodItem.qty,
                            discount: ''
                        };
                        this.afs.doc(`carts/${prodItem.cartId}`).delete();
                    });
                    // console.log(cartItem);
                    // console.log(products);
                    const product = cartItem[0];
                    this.custId = this.custId.trim();
                    const orderItem = {
                        amount: 'A$ ' + otherCharge.totalAmt.toFixed(2),
                        customer: firebase.firestore().doc('/customer/' + this.custId),
                        shopper: product.shopper,
                        deliveryAddress: otherCharge.custAddress,
                        deliveryCharge: 'A$ ' + otherCharge.deliveryCharge.toFixed(2),
                        deliveryLocation: otherCharge.custAddress.latLng,
                        bookDate: firebase.firestore.FieldValue.serverTimestamp(),
                        orderDate: Math.floor(Date.now() / 1000),
                        orderCode: this.orderCode(),
                        orderId: '',
                        orderStatus: 1,
                        pickupAddress: centerLoc.location,
                        pickupLocation: pickup,
                        center: firebase
                            .firestore()
                            .doc('/riders/qbTKza18mWVzYG9NLIbmjMbrYjG2'),
                        promoId: null,
                        rider: firebase
                            .firestore()
                            .doc('/centers/' + centerLoc.cId),
                        status: 1,
                        custId: this.custId,
                        riderId: 'qbTKza18mWVzYG9NLIbmjMbrYjG2',
                        shopperId: product.shopperId,
                        email: this.email,
                        custName: this.displayName,
                        riderName: 'John',
                        shopperState: 0,
                        paymentMethod: otherCharge.paymentMethod,
                        shopperName: '',
                        product: products,
                        timeRemain: timer,
                        discount: 'A$ ' + otherCharge.discount.toFixed(2),
                        promoApplied: otherCharge.discountApplied,
                        tax: 'A$ ' + otherCharge.taxAmount.toFixed(2)
                    };
                    // console.log(orderItem);
                    this.afs
                        .collection('orders')
                        .add(orderItem)
                        .then(docRef => {
                        const neworderId = docRef.id;
                        this.afs
                            .collection('orders')
                            .doc(neworderId)
                            .update({ orderId: neworderId })
                            .then(() => {
                            // console.log('Booking Successfully');
                            // this.router.navigateByUrl('cart');
                            resolve('Cart to Order Successfully');
                            document.body.scrollTop = document.documentElement.scrollTop = 0;
                        });
                    }).catch(error => {
                        console.error('Error adding document: ', error);
                    });
                });
            });
            // promise.then(value => console.log(value));
        });
    }
    changeOrder(orderId, status) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            // console.log(orderId, status);
            this.afs
                .collection('orders')
                .doc(orderId)
                .update({ orderStatus: status });
        });
    }
    buyNow(product) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            //
        });
    }
    orderCode() {
        const newpin = Math.round(Math.random() * 1000000);
        const orderCode = 'GM' + this.pad(newpin, 6, null);
        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) {
        this.size = size;
    }
};
OrdersService = tslib_1.__decorate([
    Injectable({
        providedIn: 'root'
    }),
    tslib_1.__metadata("design:paramtypes", [AngularFirestore,
        Router,
        ServiceService,
        SubjectService])
], OrdersService);
export { OrdersService };
//# sourceMappingURL=order.service.js.map