'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _analyticsNode = require('analytics-node');

var _analyticsNode2 = _interopRequireDefault(_analyticsNode);

var _commander = require('commander');

var _commander2 = _interopRequireDefault(_commander);

var _package = require('../../package.json');

var _package2 = _interopRequireDefault(_package);

var _debug = require('./debug');

var _debug2 = _interopRequireDefault(_debug);

var _session = require('./session');

var _session2 = _interopRequireDefault(_session);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* eslint no-underscore-dangle: "warn" */
const { debug } = (0, _debug2.default)('utils-analytics');

const STG_KEY = 'CCupheBjgV6WI0emy3oRUnDyjQ8ngmgB';
const PROD_KEY = 'fLDtpYXRjFYnHlp1gvzl4I3Gv8gDoQ8m';

const ANALYTICS_WRITE_KEY = process.env.SYNCANO_ENV === 'test' ? STG_KEY : PROD_KEY;
const analytics = new _analyticsNode2.default(ANALYTICS_WRITE_KEY, {
  flushAt: 5,
  flushAfter: 300
});

const identify = details => {
  debug('identify');
  analytics.identify({
    userId: details.id,
    traits: {
      'First name': details.first_name,
      'Last name': details.last_name,
      source: 'Sign up',
      email: details.email,
      is_active: details.is_active
    }
  });
  analytics.alias({
    previousId: details.email,
    userId: details.id
  });
};

const track = (eventName, params = {}) => {
  debug('track');

  const props = Object.assign({
    version: _package2.default.version
  }, params);

  if (_session2.default.project) {
    props.instance = _session2.default.project.instance;
  }

  const trackParams = {
    properties: props,
    event: eventName
  };

  if (_session2.default.userId) {
    trackParams.userId = _session2.default.userId;
    analytics.track(trackParams);
  }
};

const trackCommand = (options, additionalParams = {}) => {
  debug('trackCommand');
  const cmd = _lodash2.default.find(options, option => option instanceof _commander2.default.Command);
  debug('trackCommand parent', cmd.parent._name);
  const parent = cmd.parent._name === 'cli' ? null : cmd.parent._name.split('-').slice(-1)[0];

  const props = Object.assign({
    version: cmd.parent.version(),
    args: cmd.parent.rawArgs.slice(2).join(' '),
    group: cmd._group,
    type: 'command'
  }, additionalParams);

  let eventName = `CLI command: ${cmd.name()}`;
  if (parent) {
    eventName = `CLI command: ${parent} ${cmd.name()}`;
  }

  track(eventName, props);
};

exports.default = {
  identify,
  track,
  trackCommand
};
module.exports = exports['default'];
//# sourceMappingURL=analytics.js.map