'use strict';

/**
 * Created by godsong on 16/7/6.
 */
var Path = require('path');
var Transformer = require('weex-transformer');
var builder = require('weex-builder');
var Fs = require('fs-extra');
var Config = require('./Config');
var Mkdirp = require('mkdirp');
var chalk = require('chalk');

exports.loader = function (source) {
  var targetPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';

  return new Promise(function (resolve, reject) {
    var ext = Path.extname(source);
    var basename = ext ? Path.basename(source, ext) : source;
    var targetDir = Path.join(__dirname, '../../frontend/', Config.bundleDir, targetPath);
    builder.build(source, targetDir, Config.webpackConfig, function (err, output, json) {
      if (err) {
        console.log(chalk.red('Build failed!'));
        console.error(chalk.red(err));
        return reject(err);
      } else {
        console.log('Build completed!\nChild');
        console.log(output.toString());
        console.log('Time: ' + chalk.bold(json.time) + 'ms');
        resolve(targetDir + '/' + basename + '.js');
      }
    });
  });
};
exports.transformer = function (source) {
  var targetPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';

  return new Promise(function (resolve, reject) {
    Fs.readFile(source, function (err, fileContent) {
      if (err) {
        console.error(err);
        return reject(err);
      }
      var output = Transformer.transform(Path.basename(source, '.we'), fileContent.toString());
      var targetDir = Path.join(__dirname, '../../frontend/', Config.bundleDir, targetPath, Path.basename(source, '.we') + '.js');
      Mkdirp.sync(Path.dirname(targetDir));
      Fs.writeFileSync(targetDir, output.result);
      resolve(targetDir);
    });
  });
};
exports.copy = function (source) {
  var targetPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';

  return new Promise(function (resolve, reject) {
    var targetDir = Path.join(__dirname, '../../frontend/', Config.bundleDir, targetPath, Path.basename(source));
    Mkdirp.sync(Path.dirname(targetDir));
    var input = Fs.createReadStream(source);
    var output = Fs.createWriteStream(targetDir);
    input.pipe(output, {
      end: false
    });
    input.on('end', function () {
      output.end();
      resolve(targetDir);
    });
  });
};