import { Injectable } from '@angular/core';
import {
  AngularFirestore,
  AngularFirestoreDocument,
  AngularFirestoreCollection
} from '@angular/fire/firestore';
import { Router, ActivatedRoute } from '@angular/router';
import { Products } from './services/product';
import { Cart, CartItem } from './services/cart';
import { ServiceService } from './service.service';
import * as firebase from 'firebase';
import { take } from 'rxjs/operators';
import { User } from './services/user';
import { from } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CartsService {
  size: string;
  color: string;
  custId: string;
  prodId: string;
  cart: Cart;
  user: User;
  carts: CartItem[] = [];
  cartTotal: number;

  constructor(
    public afs: AngularFirestore,
    public router: Router,
    public service: ServiceService
  ) {
    this.custId = '';
    this.carts = [];
    const users = this.service.get('user').then(data => {
      if (data) {
        data = JSON.parse(data);
        this.custId = data.uid;
        // console.log(this.custId);
      }
    });
  }

  public async buyNow(product: Products) {
    this.prodId = product.prodId;
    const prodRef = firebase
      .firestore()
      .collection('products')
      .doc(this.prodId);

    this.size = this.size === undefined ? product.size[0] : this.size;
    this.color = this.color === undefined ? product.color[0] : this.color;

    const cartRef: AngularFirestoreCollection<any> = this.afs.collection(
      'carts',
      ref =>
        ref
          .where('size', '==', this.size)
          .where('color', '==', this.color)
          .where('custId', '==', this.custId)
          .where('product', '==', prodRef)
    );
    cartRef
      .valueChanges()
      .pipe(take(1))
      .subscribe(value => {
        // console.log(value);
        if (value.length === 0) {
          product.image =
            product.image === undefined
              ? '../assets/model1@3x.jpg'
              : product.image;
          const cart: Cart = {
            color: this.color,
            custId: this.custId,
            shopperId: product.shopperId,
            product: firebase.firestore().doc(`products/${this.prodId}`),
            image: product.image,
            prodId: product.prodId,
            price: product.price,
            prodName: product.prodName,
            shopper: product.shopper,
            qty: 1,
            size: this.size
          };
          // console.log(cart);
          this.afs
            .collection('carts')
            .add(cart)
            .then(docRef => {
              const neworderId = docRef.id;
              this.afs
                .collection('carts')
                .doc(neworderId)
                .update({ cartId: docRef.id })
                .then(() => {
                  // console.log('Booking Successfully');
                  document.body.scrollTop = document.documentElement.scrollTop = 0;
                });
            })
            .catch(error => {
              console.error('Error adding document: ', error);
            });
        } else {
          // console.log(value);
          // alert('Item already added in the cart');
          const cartId = value[0].cartId;
          // tslint:disable-next-line:radix
          const qty = parseInt(value[0].qty) + 1;
          this.afs
            .collection('carts')
            .doc(cartId)
            .update({ qty: `${qty}` })
            .then(() => {
              // console.log('Booking Successfully');
              document.body.scrollTop = document.documentElement.scrollTop = 0;
            });
        }
      });
  }

  public async cartList() {
    console.log('called');
    const cartRef: AngularFirestoreCollection<any> = this.afs.collection(
      'carts',
      ref => ref.where('custId', '==', this.custId)
    );
    cartRef.valueChanges().subscribe(value => {
      this.carts = [];
      const res = value;
      this.cartTotal = 0;
      if (res.length > 0) {
        res.forEach(item => {
          const cartItem: CartItem = {
            cartId: item.cartId,
            color: item.color,
            shopperId: item.shopperId,
            shopper: item.shopper,
            prodId: item.prodId,
            price: item.price,
            prodName: item.prodName,
            image: item.image,
            qty: item.qty,
            size: item.size
          };
          // console.log(item.price, item.qty);
          if (item.price) {
            this.cartTotal += item.price * item.qty;
          }
          /*const prodItem = item.product.get().then((property) => {
            const response = property.data();
            cartItem.prodName = response.prodName;
            cartItem.price = response.price;
            cartItem.image = response.image;
            cartItem.prodId = response.prodId;
            cartItem.shopperId = response.shopper;
            this.cartTotal += response.price;
          });*/
          this.carts.push(cartItem);
        });
      } else {
        // alert('No Products Found');
      }
    });
  }

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

  choose_color(color: string) {
    this.color = color;
  }

  removeCount(index) {
    // tslint:disable-next-line:radix
    const qty =
      this.carts[index].qty > 1
        ? this.carts[index].qty - 1
        : this.carts[index].qty;
    this.carts[index].qty = qty;
    // console.log(this.carts[index].qty);
    this.afs
      .collection('carts')
      .doc(this.carts[index].cartId)
      .update({
        qty: this.carts[index].qty
      });
  }

  addCount(index) {
    const qty = Number(this.carts[index].qty) + 1; // Converts string to Number
    this.cartTotal = 0;
    this.carts[index].qty = qty;
    this.afs
      .collection('carts')
      .doc(this.carts[index].cartId)
      .update({
        qty: this.carts[index].qty
      });
  }

  removeItem(index) {
    this.afs
      .collection('carts')
      .doc(this.carts[index].cartId)
      .delete();
  }

  checkPromo(promoCode: string) {
    // console.log(promoCode);
    const state = true;
    const promoRef: AngularFirestoreCollection<any> = this.afs.collection(
      'promocode',
      ref =>
        ref.where('promoCode', '==', promoCode).where('status', '==', state)
    );
    return promoRef.valueChanges();
  }
}
