const fs = require("fs");
const getUrls = require("./getUrls.json");
// const getFixtures = require("./getFixtures.json");

const postUrls = require("./postUrls.json");
const postFixtures = require("./postFixtures.json");
const postErrorFixtures = require("./postErrorFixtures.json");

const putUrls = require("./putUrls.json");
const putFixtures = require("./putFixtures.json");
const putErrorFixtures = require("./putErrorFixtures.json");

let settings = {
  getFixtures200: [],
  postFixtures200: [],
  postFixtures201: [],
  postFixtures400: [],
  putFixtures200: [],
  putFixtures400: [],
};
let template = fs.readFileSync("./template.js").toString();
let templateFunction = fs.readFileSync("./templateFunction.js").toString();

Object.keys(getUrls).forEach((key) => {
  // if (getFixtures[key] === undefined) return;
  console.log(key);
  // updateSettings(key, "GET", getUrls[key], getFixtures[key].data, 200);
  updateSettings(key, "GET", getUrls[key], null, 200);
});

Object.keys(postUrls).forEach((key) => {
  if (postFixtures[key] === undefined) return;
  console.log(key);
  updateSettings(key, "POST", postUrls[key], postFixtures[key], postFixtures[key] === null ? 201 : 200);
});

Object.keys(postUrls).forEach((key) => {
  if (postErrorFixtures[key] === undefined) return;
  console.log(key);
  updateSettings(key, "POST", postUrls[key], postErrorFixtures[key], 400);
});

Object.keys(putUrls).forEach((key) => {
  if (putFixtures[key] === undefined) return;
  console.log(key);
  updateSettings(key, "PUT", putUrls[key], putFixtures[key].data, 200);
});

Object.keys(putUrls).forEach((key) => {
  if (putErrorFixtures[key] === undefined) return;
  console.log(key);
  updateSettings(key, "PUT", putUrls[key], putErrorFixtures[key].error, 400);
});

function updateSettings(key, method, url, data, status) {
  const name = `${status}_${key}.json`;
  // fs.writeFileSync(`./fixtures/${method}/${name}`, JSON.stringify(data));

  settings[`${method.toLowerCase()}Fixtures${status}`].push(
    template
      .replace(/__KEY__/g, key)
      .replace(/__URL__/g, url)
      .replace(/__METHOD__/g, method)
      .replace(/__STATUS__/g, status)
  );
}

Object.keys(settings).forEach(key => {
  fs.writeFileSync(`./support/${key}.js`, templateFunction.replace(/__KEY__/g, key).replace(/__SETTINGS__/g, settings[key].join("\n")));
})

