import os
from datetime import datetime
# from sitecode.py.quicksql import connect_to_mariadb, sql_get_simple

CACHE_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..")) + "/cached_files/"

# Get Cursor
def check_cache(cache_key, *file_list) -> bool:
    """ Is cache out of date? """

    if not key_exists(cache_key):
        return True

    file_path = f"{CACHE_DIR}/{cache_key}"
    if not os.path.isfile(file_path):
        return True

    file_stat = os.stat(file_path)
    last_update = max(file_stat.st_mtime, file_stat.st_ctime)

    for path in file_list:
        if os.path.isdir(path):
            for main, _, files in os.walk(path):
                for f in files:
                    s = os.stat(f"{main}/{f}")
                    if (max(s.st_mtime, s.st_ctime) > last_update):
                        return True
        else:
            s = os.stat(path)
            if (max(s.st_mtime, s.st_ctime) > last_update):
                return True

    return False

def get_latest_update(cache_key: str):
    file_path = f"{CACHE_DIR}/{cache_key}"
    if not os.path.isfile(file_path):
        return None

    file_stat = os.stat(file_path)
    last_update = datetime.fromtimestamp(max(file_stat.st_mtime, file_stat.st_ctime))
    return last_update

def key_exists(cache_key: str) -> bool:
    file_path = f"{CACHE_DIR}/{cache_key}"
    return os.path.isfile(file_path)

def get_cached(cache_key: str) -> tuple[str, str]:
    file_path = f"{CACHE_DIR}/{cache_key}"

    content = ""
    with open(file_path, "r") as fp:
        content = fp.read()

    mimetype = content[0:content.find("||")]
    content = content[content.find("||") + 2:]
    return (content, mimetype)

def update_cache(cache_key: str, value: str, mime="text/html"):
    if not os.path.isdir(CACHE_DIR):
        os.mkdir(CACHE_DIR)

    file_path = f"{CACHE_DIR}/{cache_key}"
    with open(file_path, "w") as fp:
        fp.write(f"{mime}||{value}")

