#!/usr/bin/env python
#coding=utf-8

import sys, os
import getopt
import os.path
import subprocess

sys.path.append("/home/mylight/Dropbox (MyLight Systems)/R&D/Software/Scripts/Utils")
from utils_stats import *


path_to_folder = "/home/mylight/Dropbox (MyLight Systems)/R&D/Software/SauvegardeAL/SRS/Conso_exports_truncated"
fm = "%Y-%m-%d %H:%M:%S"


######################### LOADDATA
def loadData_conso(filename,limit_ts, limit_date):

	f = open(filename, 'rU')
	data = [line.strip() for line in f.readlines()[1:]]
	f.close()

	deviceName = []
	time = []
	mac = []
	power = []
	energy = []
	cost = []
	for line in data:
		items = line.split(',')
		if (float(local_2_timestamp(str(items[1]),fm)) < float(limit_ts)):
			print datetime.datetime.fromtimestamp(float(local_2_timestamp(str(items[1]),fm))).strftime(fm), limit_date
			deviceName.append(str(items[0]))
			time.append(str(items[1]))
			mac.append(str(items[2]))
			power.append(str(items[3]))
			energy.append(str(items[4]))
			cost.append(str(items[5]))

	return deviceName,time,mac,power,energy,cost


def loadDevices(filename):

	f = open(filename, 'rU')
	data = [line.strip() for line in f.readlines()[1:]]
	f.close()

	deviceId = []
	clientId = []
	inidate = []
	for line in data:
		items = re.split(r'\t+',line)
		deviceId.append(str(items[0]))
		clientId.append(str(items[1]))
		inidate.append(str(items[2]))

	return deviceId,clientId,inidate



######################### EXECUTION


#*****
def main(argv):

#	try:
#		opts, args = getopt.getopt(argv, "h", ["file=","start_from="])
#	except getopt.GetoptError, err:
#	# print help information and exit:
#		print str(err) # will print something like "option -a not recognized"
#		sys.exit(2)
#	for opt, arg in opts:
#		if (opt == '--file'):
#			filename = str(arg)

	# Load data
	print '\nLoading devices list...'
	deviceId, clientId, inidate = loadDevices("%s/devices_list_trunc.dat"%path_to_folder)

	for i in range(0,len(deviceId)):
		
		print '\nLoading data from %s/%s.csv'%(clientId[i],deviceId[i])
		deviceName,time,mac,power,energy,cost = loadData_conso("%s/%s/%s.csv"%(path_to_folder,clientId[i],deviceId[i]), local_2_timestamp(inidate[i]+' 00:00:00',fm), inidate[i])

		# Store in new file
		print '\nStoring data before %s'%inidate[i]
		f2 = open("%s/%s/%s.csv"%(path_to_folder,clientId[i],deviceId[i]), 'w') # Creates file or overwrites it if existing
		f2.write("device_label,time,mac,power (Watt),energy (Watt/s),cost\n")

		for k in range(0,len(deviceName)):
			f2.write("%s,%s,%s,%s,%s,%s\n"%(deviceName[k],time[k],mac[k],power[k],energy[k],cost[k]))
		f2.close()
		print '\nEnd.'



if __name__ == "__main__":
    main(sys.argv[1:])


sys.exit()
