#!/usr/bin/env node
/*
Mashes together a bunch of different apps to make
a single firmware JS file which can be uploaded.
*/
var path = require('path');
var ROOTDIR = path.join(__dirname, '..');
var OUTFILE = ROOTDIR+'/firmware.js';
var DEVICEID = "BANGLEJS";
var APPS = [ // IDs of apps to install
  "boot","launch","mclock","setting",
  "about","alarm","widbat","widbt","welcome"
];
var MINIFY = true;

var fs = require("fs");
var apploader = require("./lib/apploader.js");
apploader.init({
  DEVICEID : DEVICEID
});

var appfiles = [];

Promise.all(APPS.map(appid => {
  var app = apploader.apps.find(a => a.id==appid);
  if (!app) throw new Error(`App ${appid} not found`);
  return apploader.getAppFiles(app).then(files => {
    appfiles = appfiles.concat(files);
  });
})).then(() => {
  //console.log(appfiles);
  var js = "// Generated by BangleApps/bin/firmwaremaker.js\n";
  appfiles.forEach((file) => {
    js += file.cmd+"\n";
    /*if (file.crc && file.evaluate!==true) {
      js += `\x10if (E.CRC32(require('Storage').read(${JSON.stringify(file.name)}))!=${file.crc}){console.log("${file.name} invalid");FAIL++}\n`;
    }*/
  });
  // js = js.replace(/\x10/g,""); // remove the echo-off characters (for testing only)
  fs.writeFileSync(OUTFILE, js);
  console.log("Output written to "+OUTFILE);
});
