import firebase from 'firebase/app';
import 'firebase/firestore';
import { filterFieldDelete } from './firestore.utils';
export const entries = ({ userId, collection }) => {
  return new Promise(async (resolve, reject) => {
    try {
      const firestore = firebase.firestore();
      const snapshot = await firestore
        .collection(collection)
        .where('owner_id', '==', userId)
        .orderBy('updated_at', 'desc')
        .get();
      const results = snapshot.docs.map((documentSnapshot) => {
        return {
          id: documentSnapshot.id,
          data: documentSnapshot.data()
        };
      });
      resolve(results);
    }
    catch (err) {
      reject(err);
    }
  });
};
export const deleteEntry = ({ id, collection }) => {
  return new Promise(async (resolve, reject) => {
    try {
      const firestore = firebase.firestore();
      await firestore.collection(collection).doc(id).delete();
      resolve();
    }
    catch (err) {
      reject(err);
    }
  });
};
export const createEntry = ({ data, collection }) => {
  return new Promise(async (resolve, reject) => {
    const firestore = firebase.firestore();
    const now = firebase.firestore.Timestamp.now();
    data['created_at'] = now;
    data['updated_at'] = now;
    firestore
      .collection(collection)
      .add(data)
      .then((doc) => {
      resolve({
        id: doc.id,
        data
      });
    }, (err) => {
      reject(err);
    });
  });
};
export const getEntry = ({ id, collection }) => {
  return new Promise(async (resolve, reject) => {
    const firestore = firebase.firestore();
    try {
      const snapshot = await firestore.collection(collection).doc(id).get();
      if (!snapshot.exists) {
        reject('Entry not found');
        return;
      }
      const data = snapshot.data();
      resolve({
        id: snapshot.id,
        data
      });
    }
    catch (err) {
      reject(err);
    }
  });
};
export const updateEntry = ({ entry, collection }) => {
  return new Promise(async (resolve, reject) => {
    const firestore = firebase.firestore();
    const now = firebase.firestore.Timestamp.now();
    entry['data'].updated_at = now;
    try {
      await firestore.collection(collection).doc(entry['id']).set(entry['data'], { merge: true });
      resolve(filterFieldDelete(entry));
    }
    catch (err) {
      reject(err);
    }
  });
};
export const snapshotEntry = async ({ id, collection, onNext, onError }) => {
  if (!id) {
    throw new Error('Id not provided');
  }
  const firestore = firebase.firestore();
  const unsubscribe = firestore
    .collection(collection)
    .doc(id)
    .onSnapshot(async (deploySnapshot) => await onNext({
    id: deploySnapshot.id,
    data: deploySnapshot.data()
  }), ({ message }) => onError(message));
  return unsubscribe;
};
