#!/usr/bin/env node

import {EOL} from "os";
import {program} from "commander";
import {geoPath} from "d3-geo";
import {readFileSync} from "fs";
import {dirname, resolve} from "path";
import {fileURLToPath} from "url";
import {geoQuantize} from "../src/index.js";
import read from "./read.js";
import write from "./write.js";

const version = JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "../package.json"))).version;

const options = program
    .version(version)
    .usage("[options] [file]")
    .description("Convert GeoJSON to SVG.")
    .option("-o, --out <file>", "output file name; defaults to “-” for stdout", "-")
    .option("-w, --width <value>", "output width", 960)
    .option("-h, --height <value>", "output height", 500)
    .option("-p, --precision <value>", "number of output digits after the decimal point", 6)
    .option("-n, --newline-delimited", "accept newline-delimited JSON")
    .option("--fill <value>", "default fill", "none")
    .option("--stroke <value>", "default stroke", "black")
    .option("-r, --radius <value>", "default point radius", 4.5)
    .parse(process.argv)
    .opts();

if (program.args.length === 0) program.args[0] = "-";
else if (program.args.length !== 1) {
  console.error();
  console.error("  error: multiple input files");
  console.error();
  process.exit(1);
}

var reader = read(program.args[0], options.newlineDelimited, transform).then(end),
    writer = write(options.out),
    path = geoPath().pointRadius(function(d) { var p = d.properties, v; return p && (v = p["point-radius"] || p.pointRadius) != null ? v : options.radius; }),
    render = options.precision == null ? path : function(d) { return path(geoQuantize(d, options.precision)); };

reader.catch(error => {
  console.error(error.stack);
});

writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + EOL
    + "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" + EOL
    + "<!-- Generated by geo2svg " + version + ". https://d3js.org/d3-geo-projection/ -->" + EOL
    + "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\""
    + " width=\"" + +options.width + "\""
    + " height=\"" + +options.height + "\""
    + " viewBox=\"0 0 " + +options.width + " " + +options.height + "\""
    + (options.fill != "black" ? " fill=\"" + attr(options.fill) + "\"" : "")
    + (options.stroke != "none" ? " stroke=\"" + attr(options.stroke) + "\"" : "")
    + ">" + EOL);

function transform(d) {
  var p = d.properties, v;
  return writer.write("  <path"
      + ((v = d.id) != null ? " id=\"" + attr(v + "") + "\"" : "")
      + (p ? ((v = p["fill"]) != null ? " fill=\"" + attr(v + "") + "\"" : "")
        + ((v = p["fill-rule"] || p.fillRule) != null ? " fill-rule=\"" + attr(v + "") + "\"" : "")
        + ((v = p["fill-opacity"] || p.fillOpacity) != null ? " fill-opacity=\"" + attr(v + "") + "\"" : "")
        + ((v = p["stroke"]) != null ? " stroke=\"" + attr(v + "") + "\"" : "")
        + ((v = p["stroke-width"] || p.strokeWidth) != null ? " stroke-width=\"" + attr(v + "") + "\"" : "")
        + ((v = p["stroke-linecap"] || p.strokeLinecap) != null ? " stroke-linecap=\"" + attr(v + "") + "\"" : "")
        + ((v = p["stroke-linejoin"] || p.strokeLinejoin) != null ? " stroke-linejoin=\"" + attr(v + "") + "\"" : "")
        + ((v = p["stroke-miterlimit"] || p.strokeMiterlimit) != null ? " stroke-miterlimit=\"" + attr(v + "") + "\"" : "")
        + ((v = p["stroke-dasharray"] || p.strokeDasharray) != null ? " stroke-dasharray=\"" + attr(v + "") + "\"" : "")
        + ((v = p["stroke-dashoffset"] || p.strokeDashoffset) != null ? " stroke-dashoffset=\"" + attr(v + "") + "\"" : "")
        + ((v = p["stroke-opacity"] || p.strokeOpacity) != null ? " stroke-opacity=\"" + attr(v + "") + "\"" : "")
      : "")
      + (v = render(d), v ? " d=\"" + v + "\"" : "")
      + ">"
      + ((v = p && p["title"]) != null ? "<title>" + text(v + "") + "</title>" : "")
      + "</path>" + EOL);
}

function end() {
  return writer.write("</svg>" + EOL);
}

function text(string) {
  return string.replace(/[&<>]/g, function(character) {
    switch (character) {
      case "&": return "&amp;";
      case "<": return "&lt;";
      case ">": return "&gt;";
    }
  });
}

function attr(string) {
  return string.replace(/"/g, "&quot;");
}
