'use strict';
const path    = require('path');
const pack    = require('./utils/pack');
const auth    = require('./utils/auth');
const log     = require('./utils/log');
const ServiceClient = require('./utils/service-client');
const formstream = require('formstream');
const _ = require('lodash');
const debug = require('debug')('info');
const userConfig = require('../config/user');
const sysConfig = require('../config');
const i18n = require('./i18n_json');

module.exports = function (config, root, args) {
  if (!userConfig.loggedin || !userConfig[userConfig.loggedin]) {
    log.err(i18n.get('publish.loginMessage'));
    return process.exit();
  }

  if (typeof root !== 'string') {
    args = root;
    root = process.cwd();
  } else {
    root = path.join(process.cwd(), root);
  }

  var token = userConfig[userConfig.loggedin].token;
  var region = userConfig[userConfig.loggedin].region;
  var username = userConfig[userConfig.loggedin].username;
  var packageCFG;

  log.info(i18n.get('publish.regionMessage', {region}))

  try {
    packageCFG = require(path.join(root, 'package.json'));
  } catch (e) {
    log.err('parse package.json failed');
    return process.exit();
  }

  pack(packageCFG, path.join(config.root, config.cacheDir), root, config, function (err, tarPath) {
    if (err) {
      log.err(err);
      return process.exit();
    } else {
      let authArrs = token.split(':');
      if (!authArrs.length || authArrs.length < 2) return log.err(i18n.get('publish.loginMessage'));
      let userGroupId = authArrs[0];
      let regionName = authArrs[1];
      let regionURL = config.servers[regionName] && config.servers[regionName].server;
      if (!regionURL) return log.err(i18n.get('publish.regionError'));
      let to = token.substr(userGroupId.length + authArrs[1].length + 2);
      
      var client = new ServiceClient({
        endpoint: userConfig.loggedin && userConfig[userConfig.loggedin] && userConfig[userConfig.loggedin].server || sysConfig.serverDefault,
        token: sysConfig.systemToken,
      });

      var form = formstream();
      form.file('package', tarPath);
      form.field('name', packageCFG.name);
      form.field('version', packageCFG.version);
      form.field('username', username);
      form.field('userGroupId', parseInt(userGroupId));
      form.field('region', region);
      debug(`${userGroupId} publish ${packageCFG.name}@${packageCFG.version}, to ${regionURL}`);
      log.info(i18n.get('publish.publishing'));
      client.post(regionURL + 'upload', (err, data, res) => {
      // client.post('/admin/service/module/upload', {test: 1}, (err, data, res) => {
        if (err) {
          log.err(err);
          if (data) log.info(data.toString('utf8'));
          return process.exit();
        } else {
          var msg = data.toString('utf8');
          
          try {
            msg = JSON.parse(msg);
          } catch (e) {}

          if (!_.isEmpty(msg)) log.info(msg.message || msg);
          else log.info('upload successed!');
          return process.exit();
        }
      }, {dataType: 'String', stream: form, timeout: 5 * 60 * 1000, headers: form.headers()});
    }
  });
};
