/*! firestoreTransforms.js | Samuel Jones 2019 | MIT License | gist.github.com/samthecodingman */

/**
 * @file A file containing common firestore idioms used with queries
 * @author Samuel Jones 2017 (github.com/samthecodingman)
 * @license MIT
 * @module firestore-transforms
 */
 
/**
 * Cloud Firestore QuerySnapshot
 * @external "firebase.firestore.QuerySnapshot"
 * @see {@link https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot|firebase.firestore.QuerySnapshot}
 */

/**
 * Transforms the children of a given query snapshot to an array of objects
 * @param  {!external:firebase.firestore.QuerySnapshot} querySnapshot - The snapshot containing data to transform.
 * @param  {?string="id"} idFieldName - The name of the property to be set to the child's document ID. If null, the document ID is not merged into each object.
 * @return {!Object[]} - The array of children of the given query snapshot.
 * @public
 */
function childrenAsArrayOfObjects(querySnapshot, idFieldName) {
  let children = [];
  if (idFieldName === null) {
    querySnapshot.forEach(childDoc => children.push(childDoc.data()))
  } else {
    let idFieldName = (idFieldName && idFieldName + "") || "id";
    querySnapshot.forEach(childDoc => {
      children.push({...childDoc.data(), [idFieldName]: childDoc.id})
    })
  }
  return children;
}

/**
 * Transforms the children of a given query snapshot to an array of document IDs
 * @param  {!external:firebase.firestore.QuerySnapshot} querySnapshot - The snapshot containing data to transform.
 * @return {!string[]} - The array of document IDs that are children of the given query snapshot.
 * @public
 */
function childrenAsArrayOfIDs(querySnapshot) {
  let ids = [];
  querySnapshot.forEach(childDoc => ids.push(childDoc.id));
  return ids;
}

/**
 * Transforms the children of a given query snapshot to a object with each child as a mapped property.
 * @param  {!external:firebase.firestore.QuerySnapshot} querySnapshot - The snapshot containing data to transform.
 * @return {!Object} - The object that contains the children of the given query snapshot.
 * @public
 */
function childrenAsMappedObject(querySnapshot) {
  let mapObj = [];
  querySnapshot.forEach(childDoc => {
    mapObj[childDoc.id] = childDoc.data();
  })
  return mapObj;
}

module.exports = {
  childrenAsArrayOfObjects,
  childrenAsArrayOfIDs,
  childrenAsMappedObject
}