# Copyright (C) 2022 Thomas Hoppe (h0bB1T). All rights reserved.
#
# Unauthorized copying of this file via any medium is strictly prohibited.
# Proprietary and confidential.

import os

from time import time

from ..utils.dev import inf
from ..utils.io import set_addon_info, get_addon_info, addon_info_exists

class LocalAddonInfo:
    def __init__(self, p):
        if addon_info_exists():
            info = get_addon_info()
            self.st = info.get("st", 0)
            self.lx = info.get("lx", 0)
            self.ex = info.get("ex", 0)
        else:
            self.st, self.lx, self.ex = time(), 0, 0
            set_addon_info({"st": self.st, "lx": self.lx, "ex": self.ex})
        self.p = p


    def vl(self) -> bool:
        return (self.ex == 0 and (time() - self.st) < 1100**2) or self.p or (self.ex > 0 and (time() - self.lx) < 294**2)
    

    def exp(self) -> float:
        return max(0.0, (self.lx + 2*294**2) - time()) if self.ex > 0 else 0.0
    

    def cxp(self) -> bool:
        return self.exp() <= 60.0
    

    def dxp(self):
        if self.cxp():
            self.ex += 1
            self.lx = time()
            set_addon_info({"st": self.st, "lx": self.lx, "ex": self.ex})


# Used to measure timing on a specific part of the code.
class _MeasureObject:
    def __init__(self, text: str):
        self.text = text
        self.start = time()

    def finish(self):
        inf('%s: %i ms' % (self.text, int((time() - self.start) * 1000)))


# Used to measure timing on a specific part of the code.
class Measure:
    def __init__(self, text: str):
        self.text = text

    def __enter__(self):
        self._mo = _MeasureObject(self.text)
        return self._mo

    def __exit__(self, type, value, traceback):
        self._mo.finish()  


local_addon_info = LocalAddonInfo(p=os.path.exists(os.path.join(os.path.dirname(__file__), 'bi.py')))       
