#!/usr/bin/python
"""
2. Program that takes 3 cmd line args (Start date, end date, commodity type)
and prints the commodity type followed by the mean and variance of price over the specified date range

This uses Python 2.7 and beautifulsoup4
"""

import sys
import pandas as pd
import datetime
from numpy import mean, var
from calendar import month_name as mn
from os import system

def stats(url, date1, date2):
	# Obtain  data the data from a text file created separately in part 1 using the following:
	df1 = pd.read_csv('Prices_Data')

	# Check validity of the given dates
	td = datetime.date.today()
	date_ = date1.split('-')
	date1 = datetime.date(int(date_[0]), int(date_[1]), int(date_[2]))
	date1Str = '%s %s, %s' % (mn[int(date_[1])][0:3], date_[2], date_[0])
	if td == date1:
		delta = 0
	else:
		delta = int(str(td - date1).split(' ')[0])
	if date1Str not in df1['Dates'].tolist():
		if delta not in range(29):
			sys.exit('Error: cannot find the first date on the given page!')
		else:
			day = str(int(date_[2])+1)
			if len(day) == 1:
				day = '0%s' % day
			date1Str = '%s %s, %s' % (mn[int(date_[1])][0:3], day, date_[0])
			if date1Str not in df1['Dates'].tolist():
				day = str(int(date_[2])+2)
				if len(day) == 1:
					day = '0%s' % day
				date1Str = '%s %s, %s' % (mn[int(date_[1])][0:3], day, date_[0])
	date_ = date2.split('-')
	date2 = datetime.date(int(date_[0]), int(date_[1]), int(date_[2]))
	date2Str = '%s %s, %s' % (mn[int(date_[1])][0:3], date_[2], date_[0 ])
	if td == date2:
		delta = 0
	else: 
		delta = int(str(td - date2).split(' ')[0])
	if date2Str not in df1['Dates'].tolist():
		if delta not in range(29):
			sys.exit('Error: cannot find the second date on the given page!')
		else:
			day = str(int(date_[2] ) + 1)
			if len(day) == 1:
				day = '0%s' % day
			date2Str = '%s %s, %s' % (mn[int(date_[1])][0:3], day, date_[0])
			if date2Str not in df1['Dates'].tolist():
				day = str(int(date_[2] ) + 2)
				if len(day) == 1:
					day = '0%s' % day
				date2Str = '%s %s, %s' % (mn[int(date_[1])][0:3], day, date_[0])
	if date2 <= date1:
		sys.exit('Error: the second date must be later than the first!')
	
	# Find the respective rows of the given dates
	if df1['Dates'].tolist().index(date2Str):
		idx1 = df1['Dates'].tolist().index(date2Str)
	else:
		idx1 =  0
	if df1['Dates'].tolist().index(date1Str):
		idx2 = df1['Dates'].tolist().index(date1Str)
	else:
		idx2 = len(df1) - 1
	df2 = df1[idx1:idx2+1]
	
	# Find the prices between the dates
	vals = df2['Prices'].tolist()
	floats = []
	for val in vals:
		val = str(val)
		floats.append(float(val.replace(',', '')))
	
	# Calculate (using numpy) and return the mean and variance during the given dates
	avg = mean(floats)
	sigma2 = var(floats) 
	return (avg, sigma2)

if __name__ == "__main__":
	
	# Check the validity of the arguments
	if len(sys.argv) is not 4:
		sys.exit('Error: please enter exactly three arguments!')
	
	date1 = str(sys.argv[1])
	date2 = str(sys.argv[2])
	if date1.count('-') is not 2:
		sys.exit('Error: the first date is not valid!\nIt must be in the form of YYYY-MM-DD!') 
	if date2.count('-') is not 2:
		sys.exit('Error: the second date is not valid!\nIt must be in the form of YYYY-MM-DD!') 
	
	metal = str(sys.argv[3]).lower()
	if metal != 'gold' and metal != 'silver':
		sys.exit('Error: the third argument must be "gold" or "silver"!')
	
	# Prepare the appropriate url for stats()
	if 'gold' in metal:
		system('./getData gold')
		url = 'https://www.investing.com/commodities/gold-historical-data'
	elif  'silver' in metal:
		system('./getData silver')
		url = 'https://www.investing.com/commodities/silver-historical-data'
	
	# Get the desired statistics from stats() and print them
	avg, sigma2 = stats(url, date1, date2)
	
	# The following  string can be modified  as desired
	print('%s %f %f' % (metal, avg, sigma2))
