#!/usr/bin/env node
var tsp = require("typescript-parser");
var fs = require('fs');
var path = require('path');
var ts = require("typescript");

var parser = new tsp.TypescriptParser();
var excludedDirs = [
  'generated-sources'
];

var walkFileTree = function (dir, action) {
  if (typeof action !== "function") {
    return;
  }

  fs.readdirSync(dir).forEach(function (file) {
    var path = dir + "/" + file;
    var stat = fs.statSync(path);
    var extension = ".ts";
    if (stat && stat.isDirectory() && excludedDirs.indexOf(file) === -1) {
      walkFileTree(path, action);
    }
    else if (path.indexOf(extension, path.length - extension.length) !== -1) {
      action(null, path);
    }
  });
};

var dateInLong = Date.now();
var arr = [];

var basePath = path.resolve(__dirname, "src/ts/");
walkFileTree(basePath, function (err, file) {
  var content = fs.readFileSync(file).toString();
  var jsonStructure = parser.parseTypescript(ts.createSourceFile(
        file,
        content,
        ts.ScriptTarget.Latest,
        true,
        ts.ScriptKind.TS
      ),
      '/');
  jsonStructure['packageName'] = path.relative(path.resolve(__dirname, "src/ts/"),jsonStructure['filePath']);
  jsonStructure['imports'].forEach( function (val) {
    if (val.libraryName.startsWith(".")) {
      val['libraryName'] = path.resolve(path.dirname(jsonStructure['filePath']), val['libraryName']);
      val['libraryName'] = path.relative(path.resolve(__dirname, "src/ts/"), val['libraryName']);
      val['libraryName'] = path.dirname(val['libraryName']).split(path.sep).join(".");
    }
  });
  delete jsonStructure['filePath'];
  jsonStructure['packageName'] = path.dirname(jsonStructure['packageName']).split(path.sep).join( ".");
  arr.push(jsonStructure);
});
var cache = [];

fs.writeFileSync("./../.studio/typescript.metadata.json",
    JSON.stringify(arr, function (key, value) {
      if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
          // Circular reference found, discard key
          return;
        }
        // Store value in our collection
        cache.push(value);
      }
      return value;
    }));

cache = null;
console.log("typescript parse time = " + (Date.now() - dateInLong));