const path = require("path")

exports.createPages = ({ actions, graphql }) => {
  const { createPage } = actions

  return Promise.all([
    createDocumentationPages(createPage, graphql),
    createDocumentationIndexPage(createPage, graphql),
    createStandalonePages(createPage, graphql)
  ]);
}

const documentationPagesQuery = `
  {
    gcms {
      documentationPages(where: {treeView:DOCS}) {
        title
        description
        path
        createdAt
        updatedAt
        treeView
        content
        order
        section
      }
    }
  }
`

function createDocumentationPages(createPage, graphql) {
  const template = path.resolve(`src/templates/documentationPage.tsx`)

  return graphql(documentationPagesQuery)
    .then(({ errors = null, data }) => {
      if (errors) {
        return Promise.reject(errors)
      }

      const { gcms: { documentationPages } } = data;

      const pages = documentationPages
      .map(({path, title, order}) => ({ path, title, order: order || 0 }))
      .sort((a, b) => a.order > b.order ? 1 : -1 );

      documentationPages.forEach((currentPage) => {
        createPage({
          path: currentPage.path,
          component: template,
          context: {
            currentPage,
            pages
          },
        })
      })
    });
}

function createDocumentationIndexPage(createPage, graphql) {
  const template = path.resolve(`src/templates/documentationIndexPage.tsx`);

  return graphql(documentationPagesQuery)
  .then(({ errors = null, data }) => {
    if (errors) {
      return Promise.reject(errors)
    }

    const { gcms: { documentationPages } } = data;

    const pages = documentationPages
    .map((page) => ({ ...page, order: page.order || 0 }))
    .sort((a, b) => a.order > b.order ? 1 : -1 );

    return createPage({
      path: '/docs',
      component: template,
      context: {
        pages
      },
    });
  });
}


const standalonePagesQuery = `
  {
    gcms {
      documentationPages(where: {treeView:ROOT}) {
        title
        description
        path
        createdAt
        updatedAt
        treeView
        content
        order
        section
      }
    }
  }
`

function createStandalonePages(createPage, graphql) {
  const template = path.resolve(`src/templates/standalonePage.tsx`);


  return graphql(standalonePagesQuery)
    .then(({ errors = null, data }) => {
      if (errors) {
        return Promise.reject(errors)
      }

      const { gcms: { documentationPages } } = data;
  
      documentationPages.forEach((currentPage) => {
        createPage({
          path: currentPage.path,
          component: template,
          context: {
            currentPage,
          },
        })
      })
    });
}