#!/usr/pkg/bin/ruby33
# $Id: getPreds.rb 7450 2021-01-09 18:21:53Z 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.

# CO-OPS API For Data Retrieval
# API described at https://api.tidesandcurrents.noaa.gov/api/prod/

require "date"

def getPredsFn(sid, zulu)
  bd = DateTime.now.strftime("%Y%m%d")
  tz = (zulu ? "gmt" : "lst_ldt")
  if sid.include?("_")                          # -currents-
    # 2020-12, this old API still works...
    # tzcur = (zulu ? "GMT" : "LST%2fLDT")  # Yes, it matters
    # system("wget -q -O - \"https://tidesandcurrents.noaa.gov/noaacurrents/DownloadPredictions?fmt=txt&tz=#{tzcur}&t=24hr&u=1&id=#{sid}\" | grep -E ^2\\|Dir")
    sid, bin = sid.split("_")
    system("wget -q -O - \"https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?product=currents_predictions&interval=MAX_SLACK&station=#{sid}&bin=#{bin}&format=csv&units=english&time_zone=#{tz}&application=xtide&begin_date=#{bd}&range=96\" | sed -e \"s/,/   /g\"")
  else                                          # -tides-
    # product=high_low DOES NOT WORK.  You say interval=hilo.
    system("wget -q -O - \"https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?product=predictions&interval=hilo&station=#{sid}&format=csv&units=english&datum=MLLW&time_zone=#{tz}&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
