/*
 * Copyright (C) Sapphirecode - All Rights Reserved
 * This file is part of snippeteer which is released under BSD-3-Clause.
 * See file 'LICENSE' for full license details.
 * Created by Timo Hocker <timo@scode.ovh>, February 2020
 */

/* eslint-disable no-magic-numbers */
/* eslint-disable no-sync */
/* eslint-disable no-console */

'use strict';

const fs = require ('fs-extra');
const path = require ('path');
const dot_parser = require ('./dot_parser');

/**
 * copies the full template to a new folder named after arg[0]
 *
 * @param {string} folder folder to run in
 * @param {Array} args function arguments
 */
async function run (folder, args) {
  const graph = path.join (folder, args[0]);
  const migration = path.join (folder, args[1]);

  const db_migration = await dot_parser.create_migration (graph);
  await fs.writeFile (migration, db_migration, 'utf-8');
}

/**
 * checks if the arguments meet the requirements
 *
 * @param {string} folder folder to run in
 * @param {Array} args function arguments
 * @returns {boolean} true if arguments match requirements
 */
function assert (folder, args) {
  const tests = [
    {
      f:      () => (args.length === 2
        && typeof args[0] === 'string'
        && typeof args[1] === 'string'),
      reason: 'db [graph] [migration]'
    },
    {
      f:      () => (typeof folder === 'string'),
      reason: 'cwd is not a folder (internal error)'
    },
    {
      f:      () => (fs.existsSync (folder)),
      reason: 'cwd does not exist (internal error)'
    }
  ];
  for (const test of tests) {
    if (!test.f ()) {
      console.log (test.reason);
      return false;
    }
  }

  return true;
}

module.exports = { run, assert };