import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { AddressList, Address } from './services/address';
import { database } from 'firebase';
import { take } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AddressService {
  addressList: AddressList[] = [];
  constructor(
    public afs: AngularFirestore
  ) {
  }

  public async addList(userId: string) {
    const This = this;
    const state = true;
    const orderRef: AngularFirestoreCollection<any> = this.afs.collection('address', ref => ref.where('status', '==', state)
    .where('uid', '==', userId));
    orderRef.valueChanges().pipe(
        take(1) // Here you can limit to only emit once, using the take operator
      ).subscribe((value) => {
      this.addressList = [];
      const res = value;
      if (res.length > 0) {
        res.forEach((item) => {
          console.log(item);
          const address: AddressList = {
            address: item.address,
            addressType: item.addressType,
            latLng: item.latLng,
            defaultVal: item.defaultVal,
            building: item. building,
            landmark: item.landmark,
            addressId: item.addressId
          };
          this.addressList.push(address);
        });
        console.log(this.addressList);
      } else {
        // alert('No Orders Found');
      }
    });
  }

  addressCreate(data: Address) {
    this.afs.collection('address').add({}).then((docRef) => {
      data.addressId = docRef.id;
      this.afs.collection('address').doc(data.addressId).set(data).then(() => {
        console.log('Address created Successfully');
      });
    });
  }

  setDefaultAddress(addId: string, userId: string) {
    this.afs.collection('address', ref => ref.where('uid', '==', userId)).get().forEach((item) => {
        return item.docs.map(m => {
            return this.afs.doc(`address/${m.id}`).update({defaultVal: 0});
        });
    });
    this.afs.collection('address').doc(addId).update({defaultVal: 1}).then(() => {
        console.log('Address updated Successfully');
    });
  }
}
