import time
import os
import json
import glob
import traceback

class SolarDb:
    def __init__(self, filenamePrefix, config):
        self.config = config
        self.m_filenamePrefix = filenamePrefix

        # self.data = {} [<name>] = {}
        #                              ["10minute_mAsec"] = int
        #                              ["today_mAsec_min"] = int
        #                              ["today_mAsec_max"] = int
        #                              ["today_mAsec"] = int
        #                              ["prev_mAsec_min"] = int
        #                              ["prev_mAsec_max"] = int
        #                              ["prev_mAsec"] = int
        self.createEmptyDataStructure()

        daysToRead = 4; # today plus 3 previous
        for index in range(daysToRead-1, -1, -1):
            self.readDayLog(index)
        # self.reset_todays_data()

        self.fileUpdateInterval = 10 # minutes

        cur_time_full = time.time()
        cur_time_full_struct = time.localtime(cur_time_full)
        cur_10_min_block = int((cur_time_full_struct.tm_hour*60 + cur_time_full_struct.tm_min)/self.fileUpdateInterval)
        self.last_10_min_block = cur_10_min_block
        self.cur_date_str = None



        # original config stuff
        self.totalEnergy = 0.0;
        self.m_sensorNames = [];
        self.m_voltages = [];
        self.m_currents = [];
        self.m_times = [];
        self.m_date = "0000_00_00";
        self.m_filename = "unknown"
        self.m_prev_sampleWindow = -1;
        for index in xrange(6):
            emptyList = []
            self.m_voltages.append(emptyList);
            emptyList = []
            self.m_currents.append(emptyList);

        averages = {}
        averages["voltage"] = [];
        averages["current"] = [];

        for index in xrange(6):
            averages["voltage"].append( 0.0 );
            averages["current"].append( 0 );
        self.averages = averages
        self.averages_dataPoints = 0


    #~ def accumulateEnergy(self, solarData):  # probably belongs in SolarDb fixme.
        #~ # 0-panel;  1-bat 1;  2-bat 2;  3-load;  4-bat 3;  5-bat 4



        #~ powerInts = []
        #~ for index in range(len(solarData)):
            #~ value = int(solarData["current"][index])
            #~ powerInts.append(value)



        #~ panelPwr = powerInts[0]
        #~ loadPwr  = powerInts[3]

        #~ self.currentPanelPwr = int( panelPwr )
        #~ self.currentLoadPwr  = int( loadPwr )

        #~ # add new readings to totals;  assume 1 second integration window
        #~ for index in range(solarData):
            #~ self.todayStats[index]["cumulativeEnergy"] = self.todayStats[index]["cumulativeEnergy"] + int(solarData["current"][index])
            #~ self.prevStats[index]["cumulativeEnergy"] = self.prevStats[index]["cumulativeEnergy"] + int(solarData["current"][index])

            #~ if self.prevStats[index]["cumulativeEnergy"] < self.prevStats[index]["minEnergy"]:
                #~ self.prevStats[index]["minEnergy"] = self.prevStats[index]["cumulativeEnergy"];
            #~ elif self.prevStats[index]["cumulativeEnergy"] > self.prevStats[index]["maxEnergy"]:
                #~ self.prevStats[index]["maxEnergy"] = self.prevStats[index]["cumulativeEnergy"]







    def createEmptyDataStructure(self):
        self.data = {}
        for entry in self.config:
            tempVal = {}
            tempVal["10minute_mAsec"] = 0
            tempVal["10minute_mAsec_min"] = 999999999
            tempVal["10minute_mAsec_max"] = -999999999
            tempVal["10minute_count"] = 0

            tempVal["10minute_v"] = 0.0 # total volt values for use in calc of average
            tempVal["10minute_v_min"] = 999999999.0
            tempVal["10minute_v_max"] = -999999999.0
            tempVal["10minute_mA"] = 0 # total mA values for use in calc of average
            tempVal["10minute_mA_min"] = 999999999
            tempVal["10minute_mA_max"] = -999999999

            tempVal["today_mAsec"] = 0
            tempVal["today_mAsec_min"] = 999999999  # mA*Sec
            tempVal["today_mAsec_max"] = -999999999
            tempVal["today_count"] = 0
            tempVal["prev_mAsec"] = 0
            tempVal["prev_mAsec_min"] = 999999999
            tempVal["prev_mAsec_max"] = -999999999
            tempVal["prev_count"] = 0
            self.data[entry["name"]] = tempVal



    def addEntry(self, data):
        # solarData = {} ['names'] = [index] = strings
        #                ['voltage'] = [index] = float
        #                ['current'] = [index] = int

        cur_time_secs = time.time()

        # update file if needed
        reset_10min, reset_day = self.evaluate_rollovers(cur_time_secs)

        # write data entry if needed and flush old totals
        if reset_10min:
            self.write_data_to_file(cur_time_secs)