#!/usr/bin/env ruby
require 'open-uri'
require 'yaml'
require 'json'
require 'kramdown-rfc2629'
require 'kramdown-rfc/parameterset'
require 'kramdown-rfc/refxml'

# doilit -c 10.6028/NIST.SP.800-183 10.1016/j.adhoc.2015.04.007 10.1109/MIC.2012.29 10.1145/2507924.2507954


ACCEPT_CITE_JSON = {"Accept" => "application/citeproc+json"}

$verbose = false
$handle = "a"
$xml = false

litent = {}
ARGV.each do |doi|
  case doi
  when "-c"
    begin
      require 'open-uri/cached'
    rescue LoadError
      warn '*** please "gem install open-uri-cached" to enable caching'
    end
    next
  when "-v"
    $verbose = true
    next
  when /\A-h=(.*)/
    $handle = $1
    next
  when /\A-x=(.*)/
    $handle = $1
    $xml = true
    next
  when /\A-/
    warn "*** Usage: doilit [-c] [-v] [-h=handle|-x=xmlhandle] doi..."
    exit 1
  end
  cite = JSON.parse(URI("https://dx.doi.org/#{doi}").open(ACCEPT_CITE_JSON).read)
  puts cite.to_yaml if $verbose
  lit = {}
  ser = lit["seriesinfo"] = {}
  lit["title"] = cite["title"]
  if (st = cite["subtitle"]) && Array === st # defensive
    st.delete('')
    if st != []
      lit["title"] << ": " << st.join("; ")
    end
  end
  if authors = cite["author"]
    lit["author"] = authors.map do |au|
      lau = {}
      if (f = au["family"])
        if (g = au["given"])
          lau["name"] = "#{g} #{f}"
          lau["ins"] =  "#{g[0]}. #{f}"
        else
          lau["name"] = "#{f}"
#          lau["ins"] =  "#{g[0]}. #{f}"
        end
      end
      lau
    end
  end
  if iss = cite["issued"]
    if dp = iss["date-parts"]
      if Integer === (dp = dp[0])[0]
        lit["date"] = ["%04d" % dp[0], *dp[1..-1].map {|p| "%02d" % p}].join("-")
      end
    end
  end
  if (ct = cite["container-title"]) && ct != []
    info = []
    if v = cite["volume"]
      vi = "vol. #{v}"
      if (v = cite["journal-issue"]) && (issue = v["issue"])
        vi << ", no. #{issue}"
      end
      info << vi
    end
    if p = cite["page"]
      info << "pp. #{p}"
    end
    rhs = info.join(", ")
    if info != []
      ser[ct] = rhs
    else
      spl = ct.split(" ")
      ser[spl[0..-2].join(" ")] = spl[-1]
    end
  elsif pub = cite["publisher"]
    info = []
    if t = cite["type"]
      info << t
    end
    rhs = info.join(", ")
    if info != []
      ser[pub] = rhs
    else
      spl = pub.split(" ")
      ser[spl[0..-2].join(" ")] = spl[-1]
    end
  end
  lit["seriesinfo"]["DOI"] = cite["DOI"]
  while litent[$handle]
    $handle.succ!
  end
  litent[$handle] = lit
end
if $xml
  litent.each do |k, v|
    puts KramdownRFC::ref_to_xml(k, v)
  end
else
  # 1.9 compat: s/lines/each_line.to_a/
  puts litent.to_yaml.gsub(/^/, "  ").each_line.to_a[1..-1]
end
