#!/usr/bin/env python3
import argparse, os, sys
from sqlalchemy import create_engine
sys.path.insert(0, '..')
from wrds_fetch import wrds_update
import textwrap
def get_env_input():
	"""Get pg variables from command line, otherwise grep from OS."""
	parser = argparse.ArgumentParser(prog='./wrds_update', 
		formatter_class=argparse.RawDescriptionHelpFormatter,
		description=textwrap.dedent('''\
	        Functions
	        --------------------------------
	        1. Download tables from WRDS and upload to PostgreSQL.
	        2. Upload sas file to PostgreSQL.
	        '''),
		epilog='Report bugs to <ian.gow@unimelb.edu.au>.', 
		conflict_handler='resolve')
	parser._optionals.title = 'Optional arguments'
	parser.add_argument('--help', action='help', default=argparse.SUPPRESS,
                    help='Show this help message and exit')

	connection = parser.add_argument_group('Connection arguments')
	connection.add_argument('-h', type=str, dest='host', action='store', nargs='?', default=os.getenv("PGHOST"), 
	                    help='PostgreSQL host')
	connection.add_argument('-p', type=int, dest='port', action='store', nargs='?', default=5432, 
		help='PostgreSQL port')
	connection.add_argument('-d', type=str, dest='dbname', action='store', nargs='?', default=os.getenv("PGDATABASE"), 
		help='PostgreSQL database')
	connection.add_argument('-f', type=str, dest='fpath', action='store', nargs='?', help='File path')
	connection.add_argument('-t', type=str, dest='table', action='store', nargs='?', required=True, 
		help='Table name')
	connection.add_argument('-s', type=str, dest='schema', action='store', nargs='?', required=True, 
		help='WRDS library name')
	connection.add_argument('-w', type=str, dest='wrds_id', action='store', nargs='?', default=os.getenv("WRDS_ID"), 
		help='WRDS ID')
	connection.add_argument('-u', type=str, dest='pguser', action='store', nargs='?', default=os.getenv("PGUSER"), 
		help='PostgreSQL user')

	program = parser.add_argument_group('Table arguments')
	program.add_argument('--fix_missing', type=bool, metavar='', default=False, help='Fix special missing values')
	program.add_argument('--fix_cr', type=bool,  metavar='', default=False, help='Fix character')
	program.add_argument('--drop', type=str,  metavar='', default="", help='Columns to drop')
	program.add_argument('--obs', type=str,  metavar='', default="", help='Number of observations to return')
	program.add_argument('--rename', type=str,  metavar='', default="", help='Rename columns')
	program.add_argument('--force', type=str,  metavar='', default=False, help='Force update')

	args = parser.parse_args()

	# Check for connection variables
	if not args.host:
		print("Error: missing pghost. Specify database with -h.")
		quit()
	if not args.dbname:
		print("Error: missing pgdatabase. Specify database with -d.")
		quit()
	if not args.fpath:
		print("No SAS file path detected. Specify file path with -f.")
	if not args.wrds_id:
		print("Error: missing wrds_id. Specify database with -w.")
		quit()
	if not args.pguser:
		print("Error: missing pguser. Specify database with -u.")
		quit()

	print("\n**********************")
	print("Basic settings: ")
	print('pghost=', args.host)
	print('pgport=', args.port)
	print('pgdatabase=', args.dbname)
	print('file path=', args.fpath)
	print('table=', args.table)
	print('schema=', args.schema)
	print('wrds_id=', args.wrds_id)
	print('pguser=', args.pguser)
	print("**********************")
	return args

if __name__ == "__main__":
	args = get_env_input()
	engine = create_engine("postgresql://" + args.host + "/" + args.dbname)

	wrds_update(args.table, args.schema, engine, args.wrds_id, args.fpath, args.force,
		fix_missing=args.fix_missing, fix_cr=args.fix_cr, drop=args.drop, obs=args.obs, 
		rename=args.rename)
