import axios from 'axios';

import chalk from 'chalk';
import processor from './processor/index.mjs';

// const axios = require('axios');
// const chalk = require('chalk');

const API_URL = process.env.GATSBY_API_URL;

/* eslint no-console: ["error", { allow: ["log"] }] */

export async function getPreview(siteName, page = null, marketId, themeOptions) {
  return new Promise((resolve, reject) => {
    axios
      .get(
        `${API_URL}/sites/v0.1/pages/sorted?site_name=${siteName}&path=${page}&market_id=${marketId}&preview=1&relations=1`
      )
      .then((response) => {
        console.log(response);
        const pagePreview = response.data.result.pages.preview;
        const processed = processor.run(response.data.result, themeOptions);

        const { path } = processed.pages[pagePreview.market].preview[0];

        const pagePreviewProcessed = processed.pages[pagePreview.market][
          pagePreview.relation_type
          // eslint-disable-next-line no-shadow
        ].find((page) => page.path === path);

        resolve({
          marketSections: processed.market_sections[pagePreview.market],
          prefilledModules: processed.prefilled_market_modules[pagePreview.market],
          page: pagePreviewProcessed,
          allMarkets: processed.site_markets,
          siteInfo: processed.general,
        });
      })
      .catch((error) => reject(error));
  });
}

export async function getData(siteName, page = null) {
  let path = `${API_URL}/sites/v0.1/pages/sorted?site_name=${siteName}`;

  if (page) {
    path += `&path=${page}`;
  }
  path += '&reverse_order=1&relations=1';
  console.log(chalk.magenta('calling ') + chalk.whiteBright(path));

  const start = new Date();
  return new Promise((resolve, reject) => {
    axios
      .get(path)
      .then((response) => {
        const end = new Date() - start;
        console.log(chalk.green('success') + chalk.whiteBright(` calling hercules - %dms`), end);
        resolve(response.data.result);
      })
      .catch((error) => {
        reject(error.response.data.errors.join());
      });
  });
}

export async function getLocalData(fs) {
  return new Promise((resolve, reject) => {
    if (!fs.existsSync('./src/data/source/data.json')) {
      reject(new Error('Local Data file not found!'));
    }

    let response = fs.readFileSync('./src/data/source/data.json');
    response = JSON.parse(response);
    resolve(response.result);
  });
}
