'use strict';

var Hapi = require('hapi');
var IPFS = require('../core');
var debug = require('debug');
var fs = require('fs');
var path = require('path');
var log = debug('api');
log.error = debug('api:error');
var IPFSRepo = require('ipfs-repo');
var fsbs = require('fs-blob-store');

exports = module.exports = function HttpApi(repo) {
  var _this = this;

  this.ipfs = null;
  this.server = null;

  this.start = function (callback) {
    if (typeof repo === 'string') {
      repo = new IPFSRepo(repo, { stores: fsbs });
    }

    _this.ipfs = new IPFS(repo);

    console.log('Starting at %s', _this.ipfs.repo.path());

    _this.ipfs.load(function () {
      var repoPath = _this.ipfs.repo.path();
      var apiPath = path.join(repoPath, 'api');
      console.log('Finished loading');
      try {
        fs.statSync(apiPath);
        console.log('This repo is currently being used by another daemon');
        process.exit(1);
      } catch (err) {
        fs.writeFileSync(apiPath, 'api is on by js-ipfs', { flag: 'w+' });
      }

      _this.ipfs.config.show(function (err, config) {
        if (err) {
          return callback(err);
        }

        // TODO: set up cors correctly, following config
        _this.server = new Hapi.Server({
          connections: {
            routes: {
              cors: true
            }
          }
        });
        _this.server.app.ipfs = _this.ipfs;
        var api = config.Addresses.API.split('/');
        var gateway = config.Addresses.Gateway.split('/');

        // for the CLI to know the where abouts of the API
        fs.writeFileSync(apiPath, config.Addresses.API);

        // select which connection with server.select(<label>) to add routes
        _this.server.connection({
          host: api[2],
          port: api[4],
          labels: 'API'
        });
        _this.server.connection({
          host: gateway[2],
          port: gateway[4],
          labels: 'Gateway'
        });

        // load routes
        require('./routes')(_this.server);

        _this.ipfs.libp2p.start(function () {
          _this.server.start(function (err) {
            if (err) {
              return callback(err);
            }
            var api = _this.server.select('API');
            var gateway = _this.server.select('Gateway');
            console.log('API is listening on: %s', api.info.uri);
            console.log('Gateway (readonly) is listening on: %s', gateway.info.uri);
            callback();
          });
        });
      });
    });
  };

  this.stop = function (callback) {
    var repoPath = _this.ipfs.repo.path();
    fs.unlinkSync(path.join(repoPath, 'api'));
    var counter = 0;

    _this.server.stop(closed);
    _this.ipfs.libp2p.stop(closed);

    function closed() {
      if (++counter === 2) {
        callback();
      }
    }
  };
};