#!/usr/bin/python
# Helper code for the various sensor scripts
# Joseph E. Rener
# UCAR
# Boulder, CO USA
# Email: jrener@ucar.edu
# Copyright (c) 2018 UCAR
# Developed at COMET at University Corporation for Atmospheric Research and the Research Applications Laboratory at the National Center for Atmospheric Research (NCAR)
# Updated: 17 December 2018

import requests, datetime, re # pylint: disable=import-error

root = "/home/pi/3d_paws/"

# Get script arguments
def getArguments():
	file = open(root + 'scripts/input.txt', 'r')
	inputs = file.readline().split(",")
	file.close()
	# Get recording interval. If it's invalid, set it to 1
	clean_interval = ''.join(i for i in inputs[0] if i.isdigit())
	if clean_interval != "":
		interval = int(clean_interval)
		if interval < 0 and interval > 60:
			interval = 1
	else:
		interval = 1
	# Get chords toggle; set to False if there's an issue with it
	chords_toggle = inputs[1].lower()
	if chords_toggle != "true" and chords_toggle != "false":
		chords_toggle = "false"
	# Get chords id; set to 0 if theere's an issue with it or if chords_toggle is false
	clean_chords_id = ''.join(i for i in inputs[2] if i.isdigit())
	if clean_chords_id != "":
		chords_id = int(clean_chords_id)
		if chords_id < 0:
			chords_id = 0
	else:
		chords_id = 0
	# Get pressure level; set to 1013.25 if there's an issue with it
	remove_nondecimal = re.compile(r'[^\d.]+')
	clean_pressure = remove_nondecimal.sub('', inputs[3])
	pressue_level = 1013.25
	if clean_pressure != "":
		pressue_level = float(clean_pressure)
	return [int(interval), chords_toggle, int(chords_id), float(pressue_level)]
	

# Print output and/or log it
def output(show, line, filename):
    # Create stdio line and print to screen if show is True
    if show:
        print(line)
    # Open a file (name based on current date) and append data
    file = open(filename, 'a')
    line = line + '\n'
    file.write(line)
    file.close()


# Send data to the NCAR/EOL CHORDS website (requires a unique instrument_id; set to zero by default)
def reportCHORDS(chords_toggle, current_minute, interval, url):
    # Report every [interval] minutes by checking if the remainder of the current time divided by the interval is 0
	if current_minute % interval == 0 and chords_toggle == "true": 
		try:	
			requests.get(url=url)
			#output(True, url, root + 'logs/chords_testing.log')
		except:
			pass


# Format and print errors
def handleError(e):
	now = datetime.datetime.now()
	error_formatting = "%02d/%02d/%4d %02d:%02d:%02d - Error: %s."
	if e.message != "":
		print error_formatting % (now.month, now.day, now.year, now.hour, now.minute, now.second, e.message)	
	else:
		s = e[1]
		if ''.join(i for i in s if not i.isdigit()) != "":
			s = str(s)
			print error_formatting % (now.month, now.day, now.year, now.hour, now.minute, s)
		else:
			print error_formatting % (now.month, now.day, now.year, now.hour, now.minute, e.args)


