import machine
import os
import TimeUtils

class Logger():
    def __init__(self, hk_days):
        self.hk_days = hk_days
        self.TimeUtils = TimeUtils.TimeUtils()
        self.tempLogFile = True
        if not "logs" in os.listdir():
            os.mkdir("/logs")            

    def LogMessage(self, message):
        print(message)
        lfname = "/logs/temp.txt"
        if not self.tempLogFile:
            dt = machine.RTC().datetime()
            lfname = ("/logs/%04d-%02d-%02d.txt" % (dt[0], dt[1], dt[2]))
        dt = machine.RTC().datetime()
        file = open(lfname, "a")
        file.write(self.TimeUtils.DateTimeNow() + ";" + message + "\n")
        file.close()
    
    def Housekeeping(self):
        for file in os.listdir("/logs"):
            if (file.endswith(".txt")) and not (file == "temp.txt"):
                fd = file.split('.')[0].split('-')
                if (self.TimeUtils.IsOlderThanDays(fd, self.hk_days)):
                    os.remove("/logs/" + file)
                    self.LogMessage("Housekeeping: deleted logfile " + file)

    def LastLogs(self, lines):
        logfilename = "/logs/temp.txt"
        if not self.tempLogFile:
            dt = machine.RTC().datetime()
            logfilename = ("/logs/%04d-%02d-%02d.txt" % (dt[0], dt[1], dt[2]))
        bufsize = 4096
        fsize = os.stat(logfilename)[6]
        iter = 0
        with open(logfilename, "r") as logfile:
            line_count = 0
            for line in logfile:
                line_count += 1
            if (lines > line_count):
                lines = line_count
                #todo if lines from todays logfile are less than the number of requested lines, read missing lines from yesterdays logfile - only if not tempLogFile!
            if bufsize > fsize:
                bufsize = fsize - 1
            fetched_lines = []
            while True:
                iter += 1
                try:
                    logfile.seek(fsize - bufsize * iter)
                    fetched_lines.extend(logfile.readlines())
                except:
                    return "eof"
                    break
                if len(fetched_lines) >= lines or logfile.tell() == 0:
                    return "<br>".join(fetched_lines[-lines:])
                    break

    def MergeTempLogfile(self):
        if not self.tempLogFile:
            tempLines = 0
            try:
                with open("/logs/temp.txt", "r") as tempfile:
                    tlines = tempfile.readlines()
                    dt = machine.RTC().datetime()
                    with open(("/logs/%04d-%02d-%02d.txt" % (dt[0], dt[1], dt[2])), "a") as logfile:
                        for line in tlines:
                            tempLines += 1
                            logfile.write(line)
                os.remove("/logs/temp.txt")
                self.LogMessage("Merged " + str(tempLines) + " lines from temp-logfile into this logfile")
            except OSError:
                pass

    def DisableTempLogfile(self):
        self.tempLogFile = False
        self.MergeTempLogfile()