import * as tslib_1 from "tslib";
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import * as firebase from 'firebase';
let AddressService = class AddressService {
    constructor(afs) {
        this.afs = afs;
        this.addressList = [];
        this.nearestList = [];
    }
    addList(userId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const This = this;
            const state = true;
            const orderRef = 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 = {
                            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');
                }
            });
        });
    }
    defaultAddress(userId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const This = this;
            const state = true;
            const orderRef = this.afs.collection('address', ref => ref.where('status', '==', state).where('uid', '==', userId).where('defaultVal', '==', 1));
            orderRef.valueChanges().subscribe(value => {
                const res = value;
                if (res.length > 0) {
                    const item = res[0];
                    // console.log(item);
                    const address = {
                        address: item.address,
                        addressType: item.addressType,
                        latLng: item.latLng,
                        defaultVal: item.defaultVal,
                        building: item.building,
                        landmark: item.landmark,
                        addressId: item.addressId
                    };
                    this.defaultAdd = address;
                    console.log(this.defaultAdd);
                }
                else {
                    // alert('No Orders Found');
                }
            });
        });
    }
    addressCreate(data) {
        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, orderId) {
        console.log(data);
        this.afs
            .collection('orders').doc(orderId).update({ deliveryAddress: data });
    }
    setDefaultAddress(addId, userId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return yield 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) {
        this.afs
            .collection('address')
            .doc(addId)
            .delete();
    }
    getNearBy(centerId, userId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            // latitude, longitude, distance, userId
            console.log(centerId);
            if (centerId) {
                this.afs.collection('centers').doc(centerId).ref.get().then((doc) => {
                    if (doc.exists) {
                        console.log('Document data:', doc.data());
                        const center = doc.data();
                        const This = this;
                        const state = true;
                        const latitude = center.latLng._lat;
                        const longitude = center.latLng._long;
                        const lat = 0.0144927536231884;
                        const lon = 0.0181818181818182;
                        const distance = 10;
                        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 addressRef = this.afs.collection('address', ref => ref
                            .where('latLng', '>', lesserGeopoint)
                            .where('latLng', '<', greaterGeopoint)
                            .where('status', '==', state)
                            .where('uid', '==', userId));
                        addressRef.valueChanges().subscribe(value => {
                            this.nearestList = [];
                            const res = value;
                            if (res.length > 0) {
                                res.forEach(item => {
                                    // console.log(item);
                                    const address = {
                                        address: item.address,
                                        addressType: item.addressType,
                                        latLng: item.latLng,
                                        defaultVal: item.defaultVal,
                                        building: item.building,
                                        landmark: item.landmark,
                                        addressId: item.addressId
                                    };
                                    this.nearestList.push(address);
                                });
                                console.log(this.nearestList);
                            }
                            else {
                                // alert('No Orders Found');
                            }
                        });
                    }
                    else {
                        console.log('No such document!');
                    }
                });
            }
        });
    }
};
AddressService = tslib_1.__decorate([
    Injectable({
        providedIn: 'root'
    }),
    tslib_1.__metadata("design:paramtypes", [AngularFirestore])
], AddressService);
export { AddressService };
//# sourceMappingURL=address.service.js.map