'use strict';

var peerId = require('peer-id');
var BlockService = require('ipfs-block-service');
var DagService = require('ipfs-merkle-dag').DAGService;
var path = require('path');

module.exports = function (repo, opts, callback) {
  opts = opts || {};
  opts.emptyRepo = opts.emptyRepo || false;
  opts.bits = opts.bits || 2048;

  // Pre-set config values.
  var config = require('../init-files/default-config.json');

  // Verify repo does not yet exist.
  repo.exists(function (err, res) {
    if (err) {
      return callback(err);
    }
    if (res === true) {
      return callback(new Error('repo already exists'));
    }

    generateAndSetKeypair();
  });

  // Generate peer identity keypair + transform to desired format + add to config.
  function generateAndSetKeypair() {
    var keys = peerId.create({
      bits: opts.bits
    });
    config.Identity = {
      PeerID: keys.toB58String(),
      PrivKey: keys.privKey.toString('base64')
    };

    writeVersion();
  }

  function writeVersion() {
    var version = '3';

    repo.version.set(version, function (err) {
      if (err) {
        return callback(err);
      }

      writeConfig();
    });
  }

  // Write the config to the repo.
  function writeConfig() {
    repo.config.set(config, function (err) {
      if (err) {
        return callback(err);
      }

      addDefaultAssets();
    });
  }

  // Add the default assets to the repo.
  function addDefaultAssets() {
    // Skip this step on the browser, or if emptyRepo was supplied.
    var isNode = !global.window;
    if (!isNode || opts.emptyRepo) {
      return doneImport(null);
    }

    var importer = require('ipfs-data-importing');
    var blocks = new BlockService(repo);
    var dag = new DagService(blocks);

    var initDocsPath = path.join(__dirname, '../init-files/init-docs');

    importer.import(initDocsPath, dag, {
      recursive: true
    }, doneImport);

    function doneImport(err, stat) {
      if (err) {
        return callback(err);
      }

      // All finished!
      callback(null, true);
    }
  }
};