from datetime import datetime, date
from time import time
from pathlib import Path
from os import path, mkdir, makedirs
from json import dumps

__version__ = "1.546"

# All application data logging functions
class logData():
    def __init__(self, gui):
        self.gui = gui
        self.settings = gui.appSettings
        self.logFile = ""
        self.msgList = []

# Creates a new filename and directory under the chosen log directory.
#  Naming is cased on radio nodes and times logs were taken. Autogenerated filenames.
    def createTimeBasedLog(self, nodeIPs):
        if self.gui.connectedRequester == 1:
            timeNow = datetime.now()
            logTime = timeNow.strftime("LogDate: %m/%d/%y %H:%M:%S")
            fileTime = {}
            fileTime['Time'] = logTime
            self.msgList = []
            print("Time Based Log")
            today = date.today()
            nodeStr = nodeIPs[0]
            self.startDataTime = time()
            dateDirectory = "RN_NODES" + nodeStr + "_" + today.strftime("%m-%d-%y")
            dataDirectoryName = path.join(self.settings['logDirectory'],dateDirectory)
            if not path.isdir(dataDirectoryName):
                makedirs(dataDirectoryName)
            self.fileDateTime = timeNow.strftime("RNS_Log_%m_%d_%y_%H_%M_%S.json")
            logFileName = path.join(dataDirectoryName,self.fileDateTime)
            self.logFile = open(logFileName,"w")
            # if self.settings['logJson'] == 1:
            self.logFile.write(dumps(fileTime))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioStateReq))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioConfigReq))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioReqNodeIDMsg))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioReqPresetMsg))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioReqInfoMsg))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioReqStatsMsg))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioReqSlotMsg))
            self.logFile.write("\n\n")
            print(logFileName)
# Creates a new filename and directory under the chosen log directory. Subdirectory is created for Month/Year
#  log was taken. Name is based on user entered base name with 4 digit increasing file counter at the end.
    def createNameBasedLog(self):
        if self.gui.connectedRequester == 1:
            self.msgList = []
            timeNow = datetime.now()
            logTime = timeNow.strftime("LogDate: %m/%d/%y %H:%M:%S")
            fileTime = {}
            fileTime['Time'] = logTime
            logFileName = self.settings['logFile']
            logFilePath = self.settings['logDirectory']
            print("Name Based Log")
            self.startDataTime = time()
            self.logFile = logFilePath + logFileName
            tmp = Path(logFilePath)
            if tmp.is_dir() == False:
                print("Invalid Path, using base directory")
                logFilePath = "./"
            tmpDate = datetime.now()
            tmpDate = tmpDate.strftime("%B_%Y")
            logFileFullPath = logFilePath + tmpDate + "/"
            tmp = Path(logFileFullPath)
            if tmp.is_dir() == False:
                print("Creating", tmpDate, "subdirectory")
                mkdir(logFileFullPath)
            tmp = logFileName.split(".")
            tmpNum = "0000"
            logFileName = Path(logFileFullPath + tmp[0] + "_" + tmpNum + "." + tmp[1])
            if logFileName.is_file():
                tmpNum = 0
                while logFileName.is_file():        # find next file in sequence
                    stmp = "0000" + str(tmpNum)
                    stmp = "_" + stmp[len(stmp)-4:]
                    logFileTmp = logFileFullPath + tmp[0] + stmp
                    logFileName = Path(logFileTmp + "." + tmp[1])
                    tmpNum = tmpNum + 1
            self.logFile = logFileName
            self.logFile = open(self.logFile,"w")
            # if self.settings['logJson'] == 1:
            self.logFile.write(dumps(fileTime))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioStateReq))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioConfigReq))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioReqNodeIDMsg))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioReqPresetMsg))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioReqInfoMsg))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioReqStatsMsg))
            self.logFile.write("\n")
            self.logFile.write(dumps(self.gui.radioReqSlotMsg))
            self.logFile.write("\n\n")
            print(logFileName)
# Log data to chosen log file. Can save all messages, only range_info messages, or simply ranges and message IDs
    def logToFile(self, packet, nodeIPs):
        # Start new log if logfile is closed
        if self.logFile == "":
            if self.settings['logRangeInfoOnly'] == 1 and "RANGE_INFO" in packet:
                if self.settings['logDateBased'] == 0:
                    self.createNameBasedLog()
                else:
                    self.createTimeBasedLog(nodeIPs)
            if self.settings['logRangeInfoOnly'] == 0:
                if self.settings['logDateBased'] == 0:
                    self.createNameBasedLog()
                else:
                    self.createTimeBasedLog(nodeIPs)
        # check on segmented flag and start new at the right time
        if self.settings['logSegmented'] == 1:
            if (int((time() - self.startDataTime)) > int(self.settings['segmentTime'])):
                if (self.logFile != ""):
                    self.closeLogFile()
                    self.startDataTime = time()
                    if self.settings['logDateBased'] == 1:
                        self.createTimeBasedLog(nodeIPs)
                    else:
                        self.createNameBasedLog()
        # do the logging
        if packet != None:
            # if Json
            if self.settings['logJson'] == 1:
            # if range info only
                if self.settings['logRangeInfoOnly'] == 1:
                    if "RANGE_INFO" in packet.keys():
                        self.logFile.write(dumps(packet))
                        self.logFile.write("\n")
                else:
                    self.logFile.write(dumps(packet))
                    self.logFile.write("\n")
            # if csv
            else:
                msgKey = list(packet.keys())
                if self.settings['logRangeInfoOnly'] == 1:
                    if msgKey[0] == "RANGE_INFO":
                        if msgKey[0] not in self.msgList:
                            self.msgList.append(msgKey[0])
                            self.logFile.write(dumps(packet))
                            self.logFile.write("\n")
                        msg = packet['RANGE_INFO']
                        text = ""
                        for field in msg.keys():
                            text = text + str(msg[field]) + ","
                        text = text[:len(text)-1] + "\n"
                        self.logFile.write(text)
                else:
                    if msgKey[0] not in self.msgList:
                        self.msgList.append(msgKey[0])
                        self.logFile.write(dumps(packet))
                        self.logFile.write("\n")
                    msg = packet[msgKey[0]]
                    text = ""
                    for field in msg.keys():
                        text = text + str(msg[field]) + ","
                    text = text[:len(text)-1] + "\n"
                    self.logFile.write(text)

# Closes logfile if open
    def closeLogFile(self):
        if self.logFile != "":
            self.logFile.close()
            self.logFile = ""
            print("Closed Log")
