//
// Copyright 2021 Vulcanize, Inc.
//

import 'reflect-metadata';
import debug from 'debug';

import { FillCmd } from '@cerc-io/cli';
{{#if (subgraphPath)}}
import { getContractEntitiesMap } from '@cerc-io/util';
import { getGraphDbAndWatcher } from '@cerc-io/graph-node';
{{/if}}

import { Database{{#if (subgraphPath)}}, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP{{/if}} } from './database';
import { Indexer } from './indexer';

const log = debug('vulcanize:fill');

export const main = async (): Promise<any> => {
  const fillCmd = new FillCmd();
  await fillCmd.init(Database);

  {{#if (subgraphPath)}}
  const { graphWatcher } = await getGraphDbAndWatcher(
    fillCmd.config.server,
    fillCmd.clients.ethClient,
    fillCmd.ethProvider,
    fillCmd.database.baseDatabase,
    ENTITY_QUERY_TYPE_MAP,
    ENTITY_TO_LATEST_ENTITY_MAP
  );

  {{/if}}
  await fillCmd.initIndexer(Indexer{{#if (subgraphPath)}}, graphWatcher{{/if}});

  {{#if (subgraphPath)}}
  // Get contractEntitiesMap required for fill-state
  // NOTE: Assuming each entity type is only mapped to a single contract
  const contractEntitiesMap = getContractEntitiesMap(graphWatcher.dataSources);

  {{/if}}
  await fillCmd.exec({{#if (subgraphPath)}}contractEntitiesMap{{/if}});
};

main().catch(err => {
  log(err);
}).finally(() => {
  process.exit();
});

process.on('SIGINT', () => {
  log(`Exiting process ${process.pid} with code 0`);
  process.exit(0);
});
