"""
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import logging
import logrotater
import time
import datetime
from datetime import datetime, timedelta, date
import os
from glob import glob
import math as m


class Logger:
    def __init__(self):
        pass

    def __del__(self):
        pass


class lprint:
    def __init__(self, filelog, forcerotate):
        global ts
        global logfile
        with open(filelog, "a"):
            os.utime(filelog, None)
        logfilelist = glob("dbsync.log.*")
        datelimit = datetime.today() - timedelta(days=14)
        for i in logfilelist:
            filestamp = os.path.getmtime(i)
            timestamp = datetime.fromtimestamp(filestamp)
            if timestamp < datelimit:
                os.remove(i)
        logfile = filelog
        logSize = os.path.getsize(logfile)
        if logSize > 0:
            logfileSize = f"{logSize} ({self.humanbytes(logSize)})"
        # logfileSize = str(logSize).encode()
        try:
            print("Logfile Size: " + str(logfileSize))
        except:
            print("Logfile not present. Creating.")
            self.startlog()
            self.logprint("info", "Creating logfile.")
        if forcerotate == True:
            rotater = logrotater.LogRotate(prefix=logfile, verbose=True)
            rotater.rotate()
        elif logSize > 1000000:
            rotater = logrotater.LogRotate(prefix=logfile, verbose=True)
            rotater.rotate()

    def startlog(self):
        logging.basicConfig(filename=logfile, level=logging.DEBUG)

    def logprint(self, loglevel, logmessage):
        ts = time.time()
        logstamp = datetime.fromtimestamp(int(ts)).strftime("%Y-%m-%d %H:%M:%S")
        if loglevel.lower() == "debug":
            logging.debug(str(logstamp) + ":" + logmessage)
        elif loglevel.lower() == "warning":
            logging.warn(str(logstamp) + ":" + logmessage)
        elif loglevel.lower() == "info":
            logging.info(str(logstamp) + ":" + logmessage)

    def create_rotating_log(self, logpath):

        """
        Creates a rotating log
        """
        logger = logger.getLogger("Rotating Log")
        logger.setLevel(logger.INFO)

        # add a rotating handler
        # handler = RotatingFileHandler(logpath, maxBytes=config.get('global', 'statuslog_maxbytes'),
        #                               backupCount=config.get('global', 'status_logretention'))
        # logger.addHandler(handler)

    def humanbytes(self, i, binary=False, precision=2):
        MULTIPLES = [
            "B",
            "k{}B",
            "M{}B",
            "G{}B",
            "T{}B",
            "P{}B",
            "E{}B",
            "Z{}B",
            "Y{}B",
        ]
        base = 1024 if binary else 1000
        multiple = m.trunc(m.log2(i) / m.log2(base))
        value = i / m.pow(base, multiple)
        suffix = MULTIPLES[multiple].format("i" if binary else "")
        return f"{value:.{precision}f} {suffix}"

    def __del__(self):
        pass
