#!/usr/pkg/bin/ruby26
# $Id: sample.rb 7139 2019-12-27 00:32:02Z flaterco $
# Pick a random sample of stations and show comparable results from tide and
# the NOAA web service.  If a sid is given, just do that one; if CUR is
# specified, do all current refs.

# Note that this script is unable to prevent a (sub) station from being
# compared to a harmonic station, as the web site only gives you one or the
# other.

require "pg"
require_relative "getPreds.rb"

def doStation(sid, name, zulu)
  zparm = (zulu ? "y" : "n")
  system("tide -l \"#{name}\" -em pSsMm -pi 3 -z #{zparm} -tf \"%H:%M %Z\"")
  print "\n"
  getPredsFn(sid, zulu)
  print "------------------------------------------------------\n"
end

if ARGV.length != 2
  STDERR.puts "Usage: sample.rb y|n N    (for sample of size N)"
  STDERR.puts "    or sample.rb y|n sid  (for single station check)"
  STDERR.puts "    or sample.rb y|n CUR  (for all legacy current refs)"
  STDERR.puts "   y = UTC; n = LST/LDT"
  STDERR.puts "Don't forget to set HFILE_PATH first."
elsif ARGV[1] == "CUR"
  db = PG::Connection.open(:dbname => "harmbase2")
  query = db.exec("select station_id, name from reference_stations where date_imported < '2019-01-01' and (units = 'knots' or units = 'knots^2')")
  stations = query.values
  stations.each {|station|
    doStation(station[0], station[1], ARGV[0] == "y")
  }
elsif ARGV[1].length < 5
  sampsize = ARGV[1].to_i
  db = PG::Connection.open(:dbname => "harmbase2")
  query = db.exec("select station_id, name from data_sets")
  stations = query.values
  stations.sample(sampsize).each {|station|
    doStation(station[0], station[1], ARGV[0] == "y")
  }
else
  sid = ARGV[1]
  db = PG::Connection.open(:dbname => "harmbase2")
  query = db.exec("select min(name) from data_sets where station_id = $1",
		  [sid])
  name = query.getvalue(0,0)
  if name.nil?
    puts "Did not find station with sid #{sid}"
  else
    doStation(sid, name, ARGV[0] == "y")
  end
end
