/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var fs = require('fs');
var jsdom = require('jsdom');
var mkdirp = require('mkdirp');
var path = require('path');
var paths = {};

function process(src) {

  var html = fs.readFileSync(src);
  var dest = src.replace(/\.html$/, '.js');
  var license = /<!--(.*\n)+-->/im;

  jsdom.env({
    html: html,
    done: function (err, window) {

      var imports = window.document.querySelectorAll('link[rel="import"]');
      var scripts = window.document.querySelectorAll('script');
      var licenseContent = license.exec(html);
      var scriptsContent = '';

      if (licenseContent) {
        scriptsContent += licenseContent[0]
            .replace(/<!--/, '/**')
            .replace(/-->/, '**/')
      }


      for (var i = 0; i < imports.length; i++) {

        var importPath = imports[i].getAttribute('href');
        importPath = importPath.replace(/^\//, './third_party/');

        var from = path.dirname(dest);
        var to = importPath.replace(/html$/, 'js');
        var relativePath = path.relative(from, to);

        if (relativePath[0] !== '.')
          relativePath = './' + relativePath;

        scriptsContent += 'require("' + relativePath + '");\n';

        // Recursively process each import.
        if (paths[importPath])
          continue;

        paths[importPath] = true;
        process(importPath);
      }

      for (var s = 0; s < scripts.length; s++) {

        var script = scripts[s];

        script = script.textContent;

        script = script.replace(/tr\.exportTo/, 'global.tr.exportTo');
        script = script.replace(/var global = this;/, '');
        script = script.replace(/this.tr =/, 'global.tr =');
        scriptsContent += script;
      }

      dest = dest.replace(/\.\/third_party\/tracing/, '');
      dest = path.resolve('./third_party/tracing-js-converted/' + dest);
      var destFolder = path.dirname(dest);
      mkdirp(destFolder, function(err) {

        if (err) {
          throw "Failed to create folder: " + destFolder;
          return;
        }

        fs.writeFile(dest, scriptsContent, 'utf8');
      });
    }
  });

}

process('bin/index.html');