import firebase from 'firebase/app';
import 'firebase/firestore';
export const getUserTemplates = (userId) => {
  return new Promise(async (resolve, reject) => {
    try {
      if (!userId) {
        resolve([]);
        return;
      }
      const firestore = firebase.firestore();
      const snapshot = await firestore
        .collection('templates')
        .where('owner_id', '==', userId)
        .orderBy('updated_at', 'desc')
        .get();
      const templates = snapshot.docs.map((documentSnapshot) => {
        return {
          id: documentSnapshot.id,
          data: documentSnapshot.data()
        };
      });
      resolve(templates);
    }
    catch (err) {
      reject(err);
    }
  });
};
export const createTemplate = (templateData) => {
  return new Promise(async (resolve, reject) => {
    const firestore = firebase.firestore();
    const now = firebase.firestore.Timestamp.now();
    templateData.created_at = now;
    templateData.updated_at = now;
    firestore
      .collection('templates')
      .add(templateData)
      .then(async (doc) => {
      resolve({
        id: doc.id,
        data: templateData
      });
    }, (err) => {
      reject(err);
    });
  });
};
export const updateTemplate = (template) => {
  return new Promise(async (resolve, reject) => {
    const firestore = firebase.firestore();
    const now = firebase.firestore.Timestamp.now();
    template.data.updated_at = now;
    try {
      await firestore.collection('templates').doc(template.id).set(template.data, { merge: true });
      resolve(template);
    }
    catch (err) {
      reject(err);
    }
  });
};
