#!/usr/pkg/bin/ruby26
# $Id: getPreds.rb 7059 2019-06-15 19:41:17Z flaterco $
# Given: station ID or sid-plus
# Get:  predictions in 24-hr text format from NOAA web service

# I made a standalone script for this because it changes and gets more
# complicated every year.

# API described at https://tidesandcurrents.noaa.gov/api/
# Could not get it to work for currents.

require "date"

def getPredsFn(sid, zulu)
  tztid = (zulu ? "gmt" : "lst_ldt")
  tzcur = (zulu ? "GMT" : "LST%2fLDT")  # Yes, it matters
  if sid.include?("_")
    # Currents: still using this old system
    system("wget -q -O - \"https://tidesandcurrents.noaa.gov/noaacurrents/DownloadPredictions?fmt=txt&tz=#{tzcur}&t=24hr&u=1&id=#{sid}\" | grep -E ^2\\|Dir")
  else
    bd = DateTime.now.strftime("%Y%m%d")
    # Could not get this API to work for currents at all, bin or no bin.
    # product=high_low DOES NOT WORK.  You say interval=hilo.
    system("wget -q -O - \"https://tidesandcurrents.noaa.gov/api/datagetter?product=predictions&interval=hilo&station=#{sid}&format=csv&units=english&datum=MLLW&time_zone=#{tztid}&application=xtide&begin_date=#{bd}&range=96\" | sed -e \"s/,/   /g\"")
  end
end

# Only for command line use
if __FILE__==$0
  if ARGV.length != 2
    puts "Usage: getPreds.rb y|n sid     # for tides"
    puts "       getPreds.rb y|n sidplus # for currents"
    puts "   y = UTC; n = LST/LDT"
    exit
  end
  getPredsFn(ARGV[1], ARGV[0] == "y")
end
