#!C:/Users/administrator.AUTDOM01/AppData/Local/Programs/Python/Python36-32/python.exe

import os
import sys
import shutil
import time
import datetime
import mysql.connector 

import default_setting

# Get Current Path
dir_path = os.path.dirname(os.path.realpath(__file__))

# Create IDOC Segments from Closed Receipt		
def setAged(connection, currentDate):

# Get Current TimeStamp
	ts = time.time()
	currentTs = datetime.datetime.fromtimestamp(ts).strftime('_%Y-%m-%d_%H:%M:%S')
	ts = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')	
	
	try:			
# Get Document_closed id
		cursor = connection.cursor()
		dataQuery = "SELECT id FROM inventory_status WHERE lower(inventory_status_code)='aged' LIMIT 1"
		try:
			cursor.execute(dataQuery) 
			row = cursor.fetchone()
			invStsId = row[0]
		except Exception as Err:
			invStsId = 11

# If Inventory_master expiry_date < current date - flag as 'aged'
		dataQuery = "UPDATE inventory_master SET inventory_status_id='"+str(invStsId)+"', last_updated=now() WHERE expiry_date IS NOT null AND substr(expiry_date,1,10)<= '"+str(currentDate)+"'"
		try:
			cursor.execute(dataQuery)
			connection.commit()
		except UnboundLocalError:
			raise 'Update Error'
		finally:
			cursor.close()

	except UnboundLocalError as e:
		return "FAIL-"+str(e)
	
	try:
		return "OK  -setaged - "+str(currentDate)
	except UnboundLocalError:
		return "FAIL-Update Error "+currentDate+" "+dataQuery
	
def getts():
	ts = time.time()
	ts = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
	return ts

def main():
	result = "FAIL-"
	
# Default Connection / System Settings
	defaults = default_setting.defaultSettings()
# mySql Connector
	connection = mysql.connector.connect(user=defaults['dbuser'], password=defaults['dbpwd'],host=defaults['dbhost'],database=defaults['dbase'])
# timestamp
	ts = getts()

# check for Input Date
	if (len(sys.argv)>1):
		ts = sys.argv[1]
		
# Get Closed Picks & return Idoc values
	result = setAged(connection,ts)
	
	return result
				
if __name__ == '__main__':
	result = main()
	print(result)