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

@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().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) {
    console.log(data);
    this.afs
      .collection('address')
      .add({})
      .then(docRef => {
        data.addressId = docRef.id;
        this.afs
          .collection('address')
          .doc(data.addressId)
          .set(data)
          .then(() => {
            this.setDefaultAddress(data.addressId, data.uid);
            // console.log('Address created Successfully');
          });
      });
  }


  changeAddress(data: Address, orderId) {
    console.log(data);
    this.afs
      .collection('orders').doc(orderId).update({ deliveryAddress: data });
  }

  async setDefaultAddress(addId: string, userId: string) {
    return await new Promise(resolve => {
      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 });
          });
        });
      setTimeout(() => {
        console.log(addId);
        this.afs
          .collection('address')
          .doc(addId)
          .update({ defaultVal: 1 })
          .then(() => {
            resolve(true);
            console.log('Address updated Successfully');
          });
      }, 1000);
    });
  }

  deleteAddress(addId: string) {
    this.afs
      .collection('address')
      .doc(addId)
      .delete();
  }
}
