// inspired by https://github.com/lydell/source-map-concat

var fs = require('fs');
var path = require('path');
var concat = require('source-map-concat');
var glob = require('glob');

var resolveSourceMapSync = require('source-map-resolve').resolveSourceMapSync;
var createDummySourceMap = require('source-map-dummy');

// console.log(process.argv);

var sourceWorkingDirectory = null;
var sourceFiles = null;
var output = null;
var sourceMaps = false;

if (process.argv.length < 4 || process.argv.length > 6) {
  throw new Error('invalid arguments');
}

process.argv.forEach(function (argument, index) {
  if (index > 1) {
    if (index === 2) {
      sourceWorkingDirectory = argument;
    } else if (index === 3) {
      sourceFiles = sourceWorkingDirectory + '/' + argument;
    } else if (index === 4) {
      output = sourceWorkingDirectory + '/' + argument;
    } else if (index === 5) {
      sourceMaps = argument == 'true'; // intentionally loose ==
    }
  }
});

// console.log(sourceWorkingDirectory, sourceFiles, output, sourceMaps);

glob(sourceFiles, {
  nodir: true,
  nosort: true
}, function (error, files) {
  // console.log(error, files);
  // files is an array of filenames.
  // If the `nonull` option is set, and nothing
  // was found, then files is ["**/*.js"]
  // er is an error object or null.
  if (error) {
    throw error;
  }
  sourceFiles = files.map(function(file) {
    return {
      source: file,
      code: '/** Source: ' + file + ' */\n' + fs.readFileSync(file).toString()
    }
  });

  if (sourceMaps) {
    sourceFiles.forEach(function (file) {
      var previousMap = resolveSourceMapSync(file.code, file.source, fs.readFileSync);
      if (previousMap) {
        file.map = previousMap.map;
        file.sourcesRelativeTo = previousMap.sourcesRelativeTo;
      } else {
        file.map = createDummySourceMap(file.code, {
          source: file.source,
          type: 'css'
        });
      }
    });
  }

  var concatenated = concat(sourceFiles, {
    delimiter: '\n',
    mapPath: sourceMaps ? output + '.map' : null
  });

  var outputFile = path.basename(output);

  concatenated.prepend('/* Generated by cssConcatenator.js */\n');

  if (sourceMaps) {
    concatenated.add('\n/*# sourceMappingURL=' + outputFile + '.map*/');
  }

  var result = concatenated.toStringWithSourceMap({
    file: outputFile
  });

  fs.writeFileSync(output, result.code);

  if (sourceMaps) {
    fs.writeFileSync(output + '.map', result.map.toString());
  }
});
