#!/home/conda/feedstock_root/build_artifacts/gstlal-inspiral_1694401452756/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_place/bin/python
#
# Copyright (C)
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

"""Set the GPS time at which to remove count tracker counts from"""


#
# =============================================================================
#
#                                   Preamble
#
# =============================================================================
#


from optparse import OptionParser
import urllib.parse
import urllib.request
import requests
from requests.exceptions import ConnectionError
from urllib.error import URLError
import json


#
# =============================================================================
#
#                                 Command Line
#
# =============================================================================
#


def parse_command_line():
	parser = OptionParser(
		usage = "%prog [options] registry1.txt ...",
		description = __doc__
	)
	parser.add_option("--gps-time", metavar = "seconds", type = "int", action = "append", help = "Set the gps time at which to remove count tracker counts from")
	parser.add_option("--remove", action = "store_true", help = "Remove counts at the given time")
	parser.add_option("--check", action = "store_true", help = "Check whether the given time has alread been sent successfully")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose (optional).")

	options, filenames = parser.parse_args()

	if len(filenames) < 1:
		raise ValueError("must provide the name of at least one registry file")

	if not(options.check or options.remove):
		raise ValueError("must provide at least one option out of --check and --remove")

	return options, filenames


#
# =============================================================================
#
#                                     Main
#
# =============================================================================
#


#
# parse command line
#


options, filenames = parse_command_line()


def get_url(filename):
	return ["%sremove_counts.txt" % url.strip() for url in open(filename)][0]


def check(filename, gps_time):
	url = get_url(filename)
	x = requests.get(url)
	return int(gps_time) in json.loads(x.text)


def submit(filename, gps_time):
	url = get_url(filename)
	post_data = urllib.parse.urlencode({"gps_time": gps_time}).encode('utf-8')
	urllib.request.urlopen(url, data = post_data)


for filename in filenames:
	for gps_time in options.gps_time:
		if options.check:
			try:
				if not check(filename, gps_time):
					print('gps-time ' + str(gps_time) + ' not in file ' + str(filename))
			except ConnectionError:
				print('could not check for gps-time ' + str(gps_time) + ' in file ' + str(filename))
		if options.remove:
			try:
				submit(filename, gps_time)
				if not check(filename, gps_time):
					print('removing counts from gps-time ' + str(gps_time) + ' from file ' + str(filename) + ' failed')
			except URLError:
				print('removing counts from gps-time ' + str(gps_time) + ' from file ' + str(filename) + ' failed')
