/* eslint-env node */
'use strict';
const Plugin = require('broccoli-plugin');
const path = require('path');

const RSVP = require('rsvp');
const mkdirp = require('mkdirp');
const clone = require('clone');
const fs = require('fs');

const { Bundler  } = require('polymer-bundler');
const { Analyzer, FSUrlLoader } = require('polymer-analyzer');
const parse5 = require('parse5');

module.exports = ElementBundler;
ElementBundler.prototype = Object.create(Plugin.prototype);
ElementBundler.prototype.constructor = ElementBundler;

function ElementBundler(inputTree, options) {
  if (!(this instanceof ElementBundler)) {
    return new ElementBundler(inputTree, options);
  }

  // Clone the options otherwise any alterations after this writer is called
  // will be picked up.
  this.options = clone(options) || {};
  this.inputTree = inputTree;
  this.outputFilepath = options.output || path.basename(options.input);
  Plugin.call(this, [inputTree]);
}

ElementBundler.prototype.bundle = function (options) {
  return new RSVP.Promise((resolve, reject) => {
    mkdirp(path.dirname(options.output), (error) => {
      if (error) {
        reject(error);
      }

      // Some debugging lines.
      // console.log(options);
      // // console.log('from:', options.input);
      // console.log('process.cwd:', process.cwd());
      // console.log('inputTree = ', this.inputTree);
      // console.log('relative:');
      // console.log(path.relative(process.cwd(), options.input));
      // // let inputPath = path.join('.', path.relative(process.cwd(), options.input));

      // console.log('trying to read file!');
      // fs.readFile(options.input, 'utf8', (err, data) => {
      //   if (err) throw err;

      //   console.log('data=', data);
      // });

      // FIXME do not use process.cwd to get relative project location, but an options parameter instead.
      let relative = path.relative(process.cwd(), options.input);
      const analyzer = new Analyzer({
        urlLoader: new FSUrlLoader(path.resolve(process.cwd()))
      });

      const bundler = new Bundler({
        analyzer
      });
      bundler.generateManifest([ relative ]).then((manifest) => {
        bundler.bundle(manifest).then((result) => {
          let html = parse5.serialize(result.documents.get(relative).ast);

          fs.writeFileSync(options.output, html);
          resolve();
        }, (error) => reject(error)).catch((error) => reject(error));
      }, (error) => reject(error)).catch((error) => reject(error));
    });
  });
};

ElementBundler.prototype.build = function () {
  // We have to clone options again as bundle changes the hash which causes
  // the hash grow when called repeatedly.
  let options = clone(this.options);
  options.output = path.join(this.outputPath, this.outputFilepath);

  options.input = path.join(this.inputPaths[0], options.input);

  return this.bundle(options);
};

@@ -1168,610 +1168,8 @@
  // 
-Some debugging lines.%0A      // console.log(options);%0A      // // console.log('from:', options.input);%0A      // console.log('process.cwd:', process.cwd());%0A      // console.log('inputTree = ', this.inputTree);%0A      // console.log('relative:');%0A      // console.log(path.relative(process.cwd(), options.input));%0A      // // let inputPath = path.join('.', path.relative(process.cwd(), options.input));%0A%0A      // console.log('trying to read file!');%0A      // fs.readFile(options.input, 'utf8', (err, data) =%3E %7B%0A      //   if (err) throw err;%0A%0A      //   console.log('data=', data);%0A      // %7D);%0A%0A      // 
 FIXM
@@ -1226,16 +1226,25 @@
 ocation,
+%0A      //
  but an 

Remove debugging lines