var fs = require("fs");
const sharp = require("sharp");

sharp.simd(false);
sharp.cache(false);

exports.onPreBootstrap = ({ store, reporter }) => {
  const { program } = store.getState();

  const dirs = [`${program.directory}/data`];

  dirs.forEach(dir => {
    if (!fs.existsSync(dir)) {
      reporter.log(`creating the ${dir} directory`);
      mkdirp.sync(dir);
    }
  });
};

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;
  const collectionTemplate = require.resolve(
    `./src/components/Collection/index.tsx`
  );
  const tagTemplate = require.resolve(`./src/components/Tag/index.tsx`);
  const operaTemplate = require.resolve(`./src/components/Opera/index.tsx`);
  const tagsLocale = [
    {
      original: "categoryEn",
      translation: "tags"
    },
    {
      original: "categoryIt",
      translation: "categorie"
    }
  ];

  const toKebabCase = str =>
    str &&
    str
      .match(
        /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g
      )
      .map(x =>
        x
          .toLowerCase()
          .replace(/ /g, "")
          .replace(/,/g, "")
          .replace(/'/g, "")
      )
      .join("-");

  // Collection query
  const collectionQuery = graphql(`
    {
      collection: allIndexJson {
        totalCount
        edges {
          node {
            parent {
              ... on File {
                relativeDirectory
              }
            }
            price
            titolo
            categoryIt
            categoryEn
          }
        }
      }
    }
  `).then(result => {
    if (result.errors) {
      console.log(result.errors[0].message);
    }
    console.log("resolved collectionQuery");
    return ({ edges, totalCount } = result.data.collection);
  });

  // // Gallery query
  // const galleryQuery = graphql(`
  //   {
  //     galleryAll: allImageSharp {
  //       edges {
  //         node {
  //           fluid(
  //             sizes: "(orientation: portrait) 50vw, (orientation: portrait) and (min-width: 750px) 30vw, (orientation: landscape) 30vw,(orientation: landscape) and (min-width: 1170px) 18vw,(orientation: landscape) and (min-width: 1800px) 16vw"
  //           ) {
  //             aspectRatio
  //             base64
  //             presentationHeight
  //             presentationWidth
  //             sizes
  //             src
  //             srcSet
  //           }
  //         }
  //       }
  //     }
  //   }
  // `).then(result => {
  //   if (result.errors) {
  //     console.log(result.errors[0].message)
  //   }
  //   console.log("resolved galleryQuery")
  //   return result.data.galleryAll.edges
  // })

  // TagIt query
  const tagsItQuery = graphql(`
    {
      tagsIt: allIndexJson {
        group(field: categoryIt) {
          totalCount
          fieldValue
        }
      }
    }
  `).then(result => {
    if (result.errors) {
      console.log(result.errors[0].message);
    }
    return result.data.tagsIt.group;
  });

  await Promise.all([
    collectionQuery,
    // galleryQuery,
    tagsItQuery
  ]).then(([{ edges: collection, totalCount }, tagsIt]) => {
    const createIndexPages = () => {
      const itemPerPage = 20;
      const numPages = Math.ceil(totalCount / itemPerPage);
      Array.from({ length: numPages }).forEach((value, i) => {
        console.log(`createPage collection ${i}`);
        createPage({
          path: i === 0 ? `/` : `/${i + 1}`,
          component: collectionTemplate,
          context: {
            currentPage: i + 1,
            // galleryAll: galleryAll,
            limit: itemPerPage,
            numPages,
            skip: i * itemPerPage,
            tagsIt
          }
        });
      });
    };

    const createOperaPages = () => {
      collection.forEach(({ node }, index) => {
        console.log(`${index}/${totalCount} createPage ${node.titolo}`);
        createPage({
          path: node.parent.relativeDirectory,
          component: operaTemplate,
          context: {
            // galleryAll: galleryAll,
            relativeDirectory: node.parent.relativeDirectory,
            tagsIt,
            titolo: node.titolo
          }
        });
      });
    };

    const createTagPagesLocale = (tags, original, translation) => {
      const itemPerPage = 20;
      tags.forEach(tag => {
        // Count how many objects for each tag
        const filtered = collection.filter(item =>
          item.node[original].includes(tag)
        );
        const numPages = Math.ceil(filtered.length / itemPerPage);
        Array.from({ length: numPages }).forEach((value, i) => {
          console.log(`createPage ${toKebabCase(tag)}/${i === 0 ? "" : i + 1}`);
          createPage({
            path:
              i === 0
                ? `/${translation}/${toKebabCase(tag)}/`
                : `/${translation}/${toKebabCase(tag)}/${i + 1}`,
            component: tagTemplate,
            context: {
              currentPage: i + 1,
              // galleryAll: galleryAll,
              limit: itemPerPage,
              numPages,
              skip: i * itemPerPage,
              tag,
              tagsIt
            }
          });
        });
      });
    };

    const uniqTags = key => {
      let uniqTags = [];
      collection.forEach(({ node }) => {
        if (node[key]) {
          uniqTags = uniqTags.concat(node[key]);
        }
      });
      return [...new Set(uniqTags)];
    };

    const createTagPages = () => {
      tagsLocale.map(item => {
        const tags = uniqTags(item.original);
        createTagPagesLocale(tags, item.original, item.translation);
      });
    };

    createIndexPages();
    createOperaPages();
    createTagPages();
  });
};
