import os
from typing import Optional, List

import config

GROUPS_FILEPATH = os.path.join(config.SCAN2REPORT_PLUGINS_FOLDER, 'groups.json')
PROFILES_FILEPATH = os.path.join(config.SCAN2REPORT_PLUGINS_FOLDER, 'profiles.json')
ALIASES_FILEPATH = os.path.join(config.SCAN2REPORT_PLUGINS_FOLDER, 'aliases.json')


class DiskFileVersioning:
    def __init__(self):
        self._mappings = {
            'groups':   GROUPS_FILEPATH,
            'profiles': PROFILES_FILEPATH,
            'aliases': ALIASES_FILEPATH,
        }

    def _file_name_to_path(self, filename: str) -> Optional[str]:
        return self._mappings.get(filename, None)

    def list_available_files(self) -> List[str]:
        return list(self._mappings.keys())

    def get_file_from_disk(self, filename: str) -> Optional[str]:
        filepath = self._file_name_to_path(filename)
        if filepath is None:
            return None

        # todo: use versioning in DB

        with open(filepath, encoding="utf8") as f:
            return f.read()

    def save_file_to_disk(self, filename: str, content: str):
        filepath = self._file_name_to_path(filename)
        if filepath is None:
            return None

        # todo: use versioning in DB

        with open(filepath, "w", encoding="utf8") as f:
            return f.write(content)
