#!/usr/bin/env node

import {program} from "commander";
import {geoGraticule} from "d3-geo";
import {readFileSync} from "fs";
import {dirname, resolve} from "path";
import {fileURLToPath} from "url";
import write from "./write.js";

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

const graticule = geoGraticule();

const options = program
    .version(version)
    .usage("[options]")
    .description("Generate a GeoJSON graticule.")
    .option("-o, --out <file>", "output file name; defaults to “-” for stdout", "-")
    .option("--extent <value>", "the major and minor extent", parseExtent)
    .option("--extent-minor <value>", "the minor extent; defaults to " + graticule.extentMajor(), parseExtent)
    .option("--extent-major <value>", "the major extent; defaults to " + graticule.extentMinor(), parseExtent)
    .option("--step <value>", "the major and minor step", parseStep)
    .option("--step-minor <value>", "the minor step; defaults to " + graticule.stepMinor(), parseStep)
    .option("--step-major <value>", "the major step; defaults to " + graticule.stepMajor(), parseStep)
    .option("--precision <value>", "the precision; defaults to " + graticule.precision(), graticule.precision)
    .parse(process.argv)
    .opts();

if (program.args.length !== 0) {
  console.error();
  console.error("  error: unexpected arguments");
  console.error();
  process.exit(1);
}

if (options.extent != null) {
  if (options.extentMinor == null) options.extentMinor = options.extent;
  if (options.extentMajor == null) options.extentMajor = options.extent;
}
if (options.step != null) {
  if (options.stepMinor == null) options.stepMinor = options.step;
  if (options.stepMajor == null) options.stepMajor = options.step;
}
if (options.extentMinor != null) graticule.extentMinor(options.extentMinor);
if (options.extentMajor != null) graticule.extentMajor(options.extentMajor);
if (options.stepMinor != null) graticule.stepMinor(options.stepMinor);
if (options.stepMajor != null) graticule.stepMajor(options.stepMajor);

var writer = write(options.out);
writer.write(JSON.stringify(graticule()) + "\n");
writer.end().catch(abort);

function parseStep(x) {
  return x = x.split(","), x.length === 1 ? [+x[0], +x[0]] : [+x[0], +x[1]];
}

function parseExtent(x) {
  return x = x.split(","), [[+x[0], +x[1]], [+x[2], +x[3]]];
}

function abort(error) {
  console.error(error.stack);
}
