from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
import logging
import MySQLdb
import subprocess
logging.basicConfig()

sched = BlockingScheduler()
f = '%Y-%m-%d %H:%M:%S'
POS = 4
STATION = 'kampala3'
STATION_CODE = 49143

def usage():
	df = subprocess.Popen(["df", "-h", "/"], stdout=subprocess.PIPE)
	output = df.communicate()[0]
	return output.split("\n")[1].split()[POS].replace("%","")

def push(now):
	# Open database connection
	db = MySQLdb.connect("plk-mysql-dev.cyrmgnxrpjc7.us-east-1.rds.amazonaws.com","radio","&.ahHAS!*Qmp","radio" )

	# prepare a cursor object using cursor() method
	cursor = db.cursor()

	# Prepare SQL query to INSERT a record into the database.
	sql = """INSERT INTO storage_status(
	        `station`, `usage`, `timestamp`, `station_code`) 
	        VALUES ('%s', '%d', '%s', '%d')""" % (STATION, int(usage()), now, STATION_CODE)
	try:
	   # Execute the SQL command
	   cursor.execute(sql)
	   # Commit your changes in the database
	   db.commit()
	except Exception as e:
	   print str(e)
	   # Rollback in case there is any error
	   db.rollback()

	# disconnect from server
	db.close()

@sched.scheduled_job('cron', hour='*/6')
def perform_task():
	now = datetime.now().strftime(f)
	push(now)
	# print usage()

sched.start()
