let fs = require('fs');
let csv = require('csv');

let countries = {},
    zones = {},
    offsdict = {},
    now = Date.now()/1000; // we need this to find zone's current DST state

function handleWrite(err,bytes) {
 if (err) {
  console.log(`Error writing to file ${err}`);
 }
}

console.log("Generating fourTwentyTz.js...");
fs.createReadStream(__dirname+'/country.csv')
  .pipe(csv.parse())
  .on('data', (r) => {
    countries[r[0]] = r[1];
  })
  .on('end', () => {
    fs.createReadStream(__dirname+'/time_zone.csv')
      .pipe(csv.parse())
      .on('data', (r) => {
        let parts = r[0].replace('_',' ').split('/');
        let city = parts[parts.length-1];
        let country ='';
        if (parts.length>2) { // e.g. America/North_Dakota/New_Salem
          country = parts[1]; // e.g. North Dakota
        } else {
          country = countries[r[1]]; // e.g. United States
        }
        zone = zones[r[0]] || { "name": `${city}, ${country}` };
        let starttime = parseInt(r[3] || "0"), // Bugger. They're feeding us blanks for UTC now
            offs = parseInt(r[4]);
        if (offs<0) {
          offs += 60*60*24;
        }
        if (starttime<now && (!("starttime" in zone) || zone.starttime<starttime)) {
            zone.starttime = starttime;
            zone.offs = Math.floor(offs/60);
        }
        zones[r[0]] = zone;
      })
      .on('end', () => {
        for (z in zones) {
          zone = zones[z];
          if (zone.offs%60) continue; // One a dem funky timezones. Ignore.
          zonelist = offsdict[zone.offs] || [];
          zonelist.push(zone.name);
          offsdict[zone.offs] = zonelist;
        }
        offsets = [];
        for (o in offsdict) {
          offsets.unshift(parseInt(o));
        }
        fs.open("fourTwentyTz.js","w", (err, fd) => {
          if (err) {
            console.log("Can't open output file");
            return;
          }
          fs.write(fd, "// Generated by mkFourTwentyTz.js\n", handleWrite);
          fs.write(fd, `// ${Date()}\n`, handleWrite);
          fs.write(fd, "// Data source: https://timezonedb.com/files/TimeZoneDB.csv.zip\n", handleWrite);
          fs.write(fd, "exports.offsets = ", handleWrite);
          fs.write(fd, JSON.stringify(offsets), handleWrite);
          fs.write(fd, ";\n", handleWrite);
          fs.write(fd, "exports.timezones = function(offs) {\n", handleWrite);
          fs.write(fd, "  switch (offs) {\n", handleWrite);
          for (i=0; i<offsets.length; i++) {
            let o = offsets[i].toString();
            fs.write(fd, `    case ${o}: return ${JSON.stringify(offsdict[o])};\n`, handleWrite);
          }
          fs.write(fd, "    default: return [\"Houston, we have a bug.\"];\n", handleWrite);
          fs.write(fd, "  }\n", handleWrite);
          fs.write(fd, "};\n", handleWrite);
          console.log('Done.');
        });
      });
  });
