#!/usr/bin/node

// Creates lib.js from icons
// npm install png-js

// Icons from https://fonts.google.com/icons

/* eslint-env node */

var imageconverter = require("../../../webtools/imageconverter.js");
var icons = JSON.parse(require("fs").readFileSync(__dirname+"/icon_names.json"));
const imgOptions = {
  mode : "1bit",
  inverted : true,
  transparent : true,
  output: "raw"
};
var PNG = require('png-js');
var IMAGE_BYTES = 76;

//var iconTests = [];

var promises = [];

icons.forEach((icon,iconIndex) => {
  // create image
  console.log("Loading "+icon.name);
  var fn = __dirname+"/"+icon.name+".png";
  console.log(fn);
  var png = new PNG(require("fs").readFileSync(fn));
  if (png.width!=24 || png.height!=24) {
    console.warn(icon.name+" should be 24x24px");
  }

  promises.push(new Promise(r => {
    png.decode(function (pixels) {
      var rgba = new Uint8Array(pixels);
      var isTransparent = false;
      for (var i=0;i<rgba.length;i+=4)
        if (rgba[i+3]<255) isTransparent=true;
      if (!isTransparent) { // make it transparent
        for (var i=0;i<rgba.length;i+=4)
          rgba[i+3] = 255-rgba[i];
      }

      imgOptions.width = png.width;
      imgOptions.height = png.height;
      var img = imageconverter.RGBAtoString(rgba, imgOptions);
      icon.index = iconIndex;
      icon.img = img;
      console.log("Loaded "+icon.name);
      if (img.length != IMAGE_BYTES) throw new Error("Image size should be 76 bytes");
      r(); // done
    });
  }));
});

Promise.all(promises).then(function() {
  // Allocate a big array of icons
  var iconData = new Uint8Array(IMAGE_BYTES * icons.length);
  icons.forEach((icon,idx) => {
    iconData.set(Array.prototype.slice.call(Buffer.from(icon.img,"binary")), idx*IMAGE_BYTES)
  });

  console.log("Saving images");
  require("fs").writeFileSync(__dirname+"/../icons.img", Buffer.from(iconData,"binary"));

  console.log("Saving library");
  require("fs").writeFileSync(__dirname+"/../lib.js", `
// Auto-generated by apps/icons/gen/generate.js

/// Get an icon based on a name from getIconNames that can be drawn with g.drawImage
exports.getIcon = function(name) {
  let match = ${JSON.stringify(","+icons.map(icon=>icon.name+"|"+icon.index).join(",")+",")}.match(new RegExp(\`,\${name.toLowerCase()}\\\\|(\\\\d+)\`))
  return require("Storage").read("icons.img", (match===null)?0:match[1]*${IMAGE_BYTES}, ${IMAGE_BYTES});
};

/// Get a list of available icon names
exports.getIconNames = function() {
  return ${JSON.stringify(icons.map(i=>i.name))};
};

/// Show a menu to allow an icon to be chosen - its name is returned
exports.showIconChooser = function() {
  return new Promise((resolve,reject) => {
    var menu = { "" : { title : /*LANG*/"Icons", back :  ()=>{E.showMenu();reject();}}}
    exports.getIconNames().forEach(name => {
      menu[\`\\0\${exports.getIcon(name)} \${name}\`] = ()=>{E.showMenu();resolve(name);};
    });
    E.showMenu(menu);
  });
};
  `);
});
