#!/usr/bin/env node
const path = require('path');
const fs = require('fs');
const program = require('commander');
const { PACKAGE_ROOT_DIR } = require('./constants');
const { startCli } = require('./utils');

const supportedVersions = ['2.1.0', '3.0.0', '3.1.0'];
const versionRegexp = new RegExp(`^(${supportedVersions.map(version => version.replace(/\./g, '\\.')).join('|')})$`)

program.version('2.1.0')
  .option('-s, --seed <path>', 'path to the seeding .json file')
  .option('-c, --contracts-version <version>', `polymath protocol version to launch (${supportedVersions.join(', ')})`, versionRegexp)
  .option('-b, --big', 'use big seed data (overrides -s option)')
  .option('-r, --registry-addresses', 'output the Polymath Registry address for each version')
  .parse(process.argv);

(async () => {
  let { seed, contractsVersion, big, registryAddresses } = program;
  let seedData;

  if (registryAddresses) {
    let output = '\n\nPolymath Registry addresses:\n==============================\n';
    supportedVersions.forEach(version => {
      const artifactPath = path.resolve(__dirname, '..', 'artifacts', version, 'PolymathRegistry.json');

      const jsonArtifact = fs.readFileSync(artifactPath, 'utf8');
      const artifact = JSON.parse(jsonArtifact);

      output = `${output}\n- ${version}: ${artifact.networks[15].address}`;
    });

    output = `${output}\n\n`;

    console.log(output);
    return;
  }

  // wrong value passed
  if (contractsVersion === true) {
    throw new Error('Contracts version must be "2.1.0", "3.0.0" or "3.1.0"');
  }
  // no value passed
  if (!contractsVersion) {
    contractsVersion = supportedVersions[supportedVersions.length - 1];
  }  

  seedData = require(`./seed/${contractsVersion}`);

  const dbPath = `${PACKAGE_ROOT_DIR}/blockchain-state/${contractsVersion}`.split('/').join(path.sep);
  await startCli(dbPath);
  let dataFile = big ? `${__dirname}/seed/seedDataBig.json` : seed || `${__dirname}/seed/seedData.json`;
  dataFile = dataFile.split('/').join(path.sep);

  console.log(`Reading seed data from "${dataFile}"`);
  await seedData(path.resolve(dataFile));
})().catch(console.log);
