import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import {
  AngularFirestore,
  AngularFirestoreDocument,
  AngularFirestoreCollection
} from '@angular/fire/firestore';
import { ServiceService } from './service.service';
import { Shopper } from './services/shopper';
import * as firebase from 'firebase';

@Injectable({
  providedIn: 'root'
})
export class ShoppersService {
  shoppers: Shopper[] = [];
  activeshoppers: Shopper[] = [];
  nearshoppers: Shopper[] = [];
  constructor(
    public afs: AngularFirestore,
    public afAuth: AngularFireAuth,
    public service: ServiceService
  ) {
    this.featuredshopperList();
    this.getNearBy(-33.87276, 151.20534, this.service.distance);
  }

  public async shopperList(centerId: any, type: string) {
    const This = this;
    const state = true;
    const orderRef: AngularFirestoreCollection<any> = this.afs.collection(
      'shoppers',
      ref => ref.where(type, '==', centerId).where('status', '==', state).orderBy('name', 'asc')
    );
    orderRef.valueChanges().subscribe(value => {
      this.shoppers = [];
      const res = value;
      if (res.length > 0) {
        res.forEach(item => {
          // console.log(item);
          const shopper: Shopper = {
            name: item.name,
            emailId: item.emailId,
            phone: item.phone,
            uid: item.uid,
            profilePhoto: item.profilePic,
            status: item.status,
            address: item.address,
            featured: item.featured,
            featuredImage: item.featuredImage,
            shopName: item.shopName,
            shopStatus: item.shopStatus,
            workingHours: item.workingHours,
            caption: item.caption,
            centre: item.centre,
            location: item.location,
            rate: item.rate,
            centerId: item.centerId
          };
          this.shoppers.push(shopper);
        });
        // console.log(this.shoppers);
      } else {
        // alert('No Orders Found');
      }
    });
  }

  public async categoryShopperList(catId = null) {
    const This = this;
    const state = true;
    this.shoppers = [];
    const itemsFound = {};
    console.log(this.shoppers);
    const catRef = this.afs.collection('shopcategories').doc(catId).get().subscribe((data) => {
      this.shoppers = [];
      console.log(data.data());
      const shoppeerList = [];
      const shoppers = data.data();
      if (shoppers && Object.keys(shoppers).length > 0) {
        Object.keys(shoppers)
          .forEach(function eachKey(key) {
            shoppeerList.push(key);
          });

        if (shoppeerList.length > 0) {

          const counter = Math.ceil(shoppeerList.length / 10);
          for (let i = 0; i < counter; i++) {
            const shopItems = [];
            for (let j = 0; j < 10; j++) {
              const k = j + (i * 10);
              if (shoppeerList.length > k) {
                shopItems.push(shoppeerList[k]);
              } else {
                break;
              }
            }
            console.log(shopItems);
            const orderRef: AngularFirestoreCollection<any> = this.afs.collection(
              'shoppers',
              ref => ref.where('uid', 'in', shopItems).where('status', '==', state).orderBy('name', 'asc')
            );

            /* this.documentosCol = this.afs.collection('shoppers', ref => ref.where('pagada', 'in', [true, false]));*/


            orderRef.valueChanges().subscribe(value => {
              console.log(value);
              const res = value;
              if (res.length > 0) {
                res.forEach(item => {
                  // console.log(item);
                  const shopper: Shopper = {
                    name: item.name,
                    emailId: item.emailId,
                    phone: item.phone,
                    uid: item.uid,
                    profilePhoto: item.profilePic,
                    status: item.status,
                    address: item.address,
                    featured: item.featured,
                    featuredImage: item.featuredImage,
                    shopName: item.shopName,
                    shopStatus: item.shopStatus,
                    workingHours: item.workingHours,
                    caption: item.caption,
                    centre: item.centre,
                    location: item.location,
                    rate: item.rate,
                    centerId: item.centerId
                  };
                  if (!itemsFound[shopper.uid]) {
                    this.shoppers.push(shopper);
                    itemsFound[shopper.uid] = true;
                  }

                });
              } else {
                // alert('No Orders Found');
              }
            });
          }
        }
      } else {
        this.shoppers = [];
        this.shoppers.length = 0;
      }


    });
    /* .then(doc => {
      if (!doc.exists) {
        console.log('No such document!');
      } else {
        console.log('Document data:', doc.data());
      }
    })
    .catch(err => {
      console.log('Error getting document', err);
    }); */


    /*const orderRef: AngularFirestoreCollection<any> = this.afs.collection(
      'shoppers',
      ref => ref.where(type, '==', centerId).where('status', '==', state).orderBy('name', 'asc')
    );
    orderRef.valueChanges().subscribe(value => {
      this.shoppers = [];
      const res = value;
      if (res.length > 0) {
        res.forEach(item => {
          // console.log(item);
          const shopper: Shopper = {
            name: item.name,
            emailId: item.emailId,
            phone: item.phone,
            uid: item.uid,
            profilePhoto: item.profilePic,
            status: item.status,
            address: item.address,
            featured: item.featured,
            featuredImage: item.featuredImage,
            shopName: item.shopName,
            shopStatus: item.shopStatus,
            workingHours: item.workingHours,
            caption: item.caption,
            centre: item.centre,
            location: item.location,
            rate: item.rate,
            centerId: item.centerId
          };
          this.shoppers.push(shopper);
        });
        // console.log(this.shoppers);
      } else {
        // alert('No Orders Found');
      }
    });*/
  }

  public async featuredshopperList() {
    const This = this;
    const state = true;
    const orderRef: AngularFirestoreCollection<any> = this.afs.collection(
      'shoppers',
      ref => ref.where('featured', '==', state).where('status', '==', state).orderBy('name', 'asc')
    );
    orderRef.valueChanges().subscribe(value => {
      this.activeshoppers = [];
      const res = value;
      if (res.length > 0) {
        res.forEach(item => {
          // console.log(item);
          const shopper: Shopper = {
            name: item.name,
            emailId: item.emailId,
            phone: item.phone,
            uid: item.uid,
            profilePhoto: item.profilePic,
            status: item.status,
            address: item.address,
            featured: item.featured,
            featuredImage: item.featuredImage,
            shopName: item.shopName,
            shopStatus: item.shopStatus,
            workingHours: item.workingHours,
            caption: item.caption,
            centre: item.centre,
            location: item.location,
            rate: item.rate,
            centerId: item.centerId
          };
          this.activeshoppers.push(shopper);
        });
        // console.log(this.activeshoppers);
      } else {
        // alert('No Orders Found');
      }
    });
  }

  public async getNearBy(latitude, longitude, distance) {
    const This = this;
    const state = true;

    const lat = 0.0144927536231884;
    const lon = 0.0181818181818182;

    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 orderRef: AngularFirestoreCollection<any> = this.afs.collection(
      'shoppers',
      ref =>
        ref
          .where('centre.latLng', '>', lesserGeopoint)
          .where('centre.latLng', '<', greaterGeopoint)
          .where('status', '==', state)
    );
    orderRef.valueChanges().subscribe(value => {
      this.nearshoppers = [];
      const res = value;
      if (res.length > 0) {
        res.forEach(item => {
          // console.log(item);
          const shopper: Shopper = {
            name: item.name,
            emailId: item.emailId,
            phone: item.phone,
            uid: item.uid,
            profilePhoto: item.profilePic,
            status: item.status,
            address: item.address,
            featured: item.featured,
            featuredImage: item.featuredImage,
            shopName: item.shopName,
            shopStatus: item.shopStatus,
            workingHours: item.workingHours,
            caption: item.caption,
            centre: item.centre,
            location: item.location,
            rate: item.rate,
            centerId: item.centerId
          };
          this.nearshoppers.push(shopper);
        });
        // console.log(this.nearshoppers);
      } else {
        // alert('No Orders Found');
      }
    });
  }
}
