# Copyright (c) TuxCare, Inc. All rights reserved.
# Licensed under TUXCARE LICENSE AGREEMENT
# https://tuxcare.com/legal/

import os

from . import config, constants, fs_utils, kcare, utils

if False:  # pragma: no cover
    from typing import Optional, Tuple, Union  # noqa: F401


def clear_cache(khash, plevel):
    # type: (str, Union[str, int]) -> None
    utils.clean_directory(os.path.join(constants.PATCH_CACHE, 'patches'), exclude_path=kcare.get_cache_path(khash, plevel, ''))


def get_current_level_path(khash, fname):
    # type: (str, Optional[str]) -> str
    prefix = config.PREFIX or 'none'
    module_dir = '-'.join([prefix, khash])
    result = (constants.PATCH_CACHE, 'modules', module_dir)  # type: Tuple[str, ...]
    if fname:
        result += (fname,)
    return os.path.join(*result)


def save_cache_latest(khash, patch_level):
    # type: (str, Union[str, int]) -> None
    fs_utils.atomic_write(get_current_level_path(khash, 'latest'), str(patch_level), ensure_dir=True)


def get_cache_latest(khash):
    # type: (str) -> Optional[kcare.LegacyKernelPatchLevel]
    path_with_latest = get_current_level_path(khash, 'latest')
    if os.path.isfile(path_with_latest):
        try:
            pl = int(open(path_with_latest, 'r').read().strip())
            return kcare.LegacyKernelPatchLevel(khash, pl)
        except (ValueError, TypeError):
            pass

    return None
