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.537"

# All application data logging functions
class logData():
    def __init__(self, gui):
        self.gui = gui
        self.settings = gui.appSettings
        self.logFile = ""
        self.needComma = False
# 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:
            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)
            timeNow = datetime.now()
            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("[")
            self.needComma = False
            self.logFile.write(dumps(self.gui.radioStateReq))
            self.logFile.write(",\n")
            self.logFile.write(dumps(self.gui.radioConfigReq))
            self.logFile.write(",\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:
            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")
            self.logFile.write("[")
            self.needComma = False
            self.logFile.write(dumps(self.gui.radioStateReq))
            self.logFile.write(",\n")
            self.logFile.write(dumps(self.gui.radioConfigReq))
            self.logFile.write(",\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):
        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)
        if self.settings['logSegmented'] == 1:
            if (int((time() - self.startDataTime)) > int(self.settings['segmentTime'])):
                if (self.logFile != ""):
                    self.logFile.write("]")
                    self.closeLogFile()
                    self.startDataTime = time()
                    if self.settings['logDateBased'] == 1:
                        self.createTimeBasedLog(nodeIPs)
                    else:
                        self.createNameBasedLog()
        if packet != None:
            if self.settings['logJson'] == 1:
                if self.settings['logRangeInfoOnly'] == 1:
                    if "RANGE_INFO" in packet:
                        if self.needComma:
                            self.logFile.write(",\n")
                            self.needComma = False
                        self.logFile.write(dumps(packet))
                        self.needComma = True
                else:
                    if self.needComma:
                        self.logFile.write(",\n")
                        self.needComma = False
                    self.logFile.write(dumps(packet))
                    self.needComma = True
            else:
                if "RANGE_INFO" in packet:
                    if self.needComma:
                        self.logFile.write(",\n")
                        self.needComma = False
                    tmp = dict()
                    tmp['RANGE_ONLY'] = dict()
                    tmp['RANGE_ONLY']['msgId'] = packet['RANGE_INFO']['msgId']
                    tmp['RANGE_ONLY']['precisionRangeM'] = packet['RANGE_INFO']['precisionRangeM']
                    self.logFile.write(dumps(tmp))
                    self.needComma = True
# Closes logfile if open
    def closeLogFile(self):
        if self.logFile != "":
            self.logFile.write("]")
            self.logFile.close()
            self.logFile = ""
            print("Closed Log")
