import Promise from 'bluebird';
import whacko from 'whacko';
import fs from 'fs';
import path from 'path';
import globby from 'globby';
import utils from 'systemjs-builder/lib/utils';
import Builder from 'systemjs-builder';
import _ from 'lodash';

export function bundle(cfg) {

  let builder = new Builder(cfg.baseURL, cfg.configPath);
  builder.config(cfg.builderCfg);

  let templates = [];
  let baseURL = path.resolve(cfg.baseURL);
  let outfile = path.resolve(baseURL, cfg.bundleName) + '.html';

  if (fs.existsSync(outfile)) {
    if (!cfg.force) {
      throw new Error(`A bundle named '${outfile}' already exists. Use the --force option to overwrite it.`);
    }
    fs.unlinkSync(outfile);
  }

  globby
    .sync(cfg.includes, {
      cwd: baseURL.replace(/\\/g, '/')
    })
    .forEach(function(file) {
      file = path.resolve(baseURL, file);
      var content = fs.readFileSync(file, {
        encoding: 'utf8'
      });

      var $ = whacko.load(content);
      var name = getCanonicalName(builder, file, 'view').replace(/!view$/g, '');

      $('template').attr('id', name);
      var template = $.html('template');
      templates.push(template);
    });

  fs.writeFileSync(outfile, templates.join('\n'));

  if (cfg.options.inject) {
    injectLink(outfile, baseURL, cfg.options.inject);
  }

  return Promise.resolve();
}


function injectLink(outfile, baseURL, inject) {
  let bundleFile = path.resolve(baseURL, path.relative(baseURL, outfile));
  var indexFile = path.resolve(baseURL, inject.indexFile);
  var destFile = path.resolve(baseURL, inject.destFile);
  var relpath = path.relative(path.dirname(indexFile), path.dirname(bundleFile)).replace(/\\/g, '/');

  let link = createLink(bundleFile, relpath);
  addLink(link, indexFile, destFile);
}

function addLink(link, indexFile, destFile){
  var content = fs.readFileSync(indexFile, {
    encoding: 'utf8'
  });

  var $ = whacko.load(content);

  if ($('link[aurelia-view-bundle][href="' + link + '"]').length === 0) {
    $('head').append('<link aurelia-view-bundle rel="import" href="' + link + '">');
  }

  fs.writeFileSync(destFile, $.html());
}

function createLink(bundleFile, relpath){
  if (!relpath.startsWith('.')) {
    return relpath ? './' + relpath + '/' + path.basename(bundleFile) : './' + path.basename(bundleFile);
  } else {
    return relpath + '/' + path.basename(bundleFile);
  }
}

function getCanonicalName(builder, file, pluginName) {
  return builder.getCanonicalName(utils.toFileURL(file) + '!' + pluginName);
}

@@ -807,24 +807,50 @@
 ion(file) %7B%0A
+      if(file != '.') %7B%0A  
       file =
@@ -881,24 +881,26 @@
 ile);%0A      
+ 
+ 
 var content 
@@ -929,24 +929,26 @@
 , %7B%0A        
+  
 encoding: 'u
@@ -962,19 +962,25 @@
     
+  
 %7D);%0A
+  
 %0A      
+  
 var 
@@ -1005,16 +1005,18 @@
 ntent);%0A
+  
       va
@@ -1088,23 +1088,27 @@
 g, '');%0A
-%0A
+  %0A 
       
+ 
 $('templ
@@ -1127,24 +1127,26 @@
 id', name);%0A
+  
       var te
@@ -1180,16 +1180,18 @@
 ;%0A      
+ 
+ 
 template
@@ -1204,24 +1204,32 @@
 (template);%0A
+      %7D%0A
     %7D);%0A%0A  f

fix to check for current path "." in file list