import os
from pathlib import Path
from typing import Union

from utils.access import DriveManager
from utils.json import load_json


KEY_GOOGLE_DRIVE = "google_drive"
KEY_SUB_DATA = "data"


class PathManager:

    def __init__(self, config: Union[dict, str, Path, None] = None):
        self.drive: DriveManager = None
        self.use_google_drive = False
        self.dir_data = ""

        self._initialize(config)

    @property
    def default(self) -> str:
        return str(Path.home())

    @property
    def config(self) -> str:
        return f"{str(Path(__file__).parent.parent)}/config/"

    @property
    def corpus(self) -> str:
        return self.dir_data + "corpus/"

    @property
    def indexes(self) -> str:
        return self.dir_data + "indexes/"

    @property
    def raw(self) -> str:
        return self.dir_data + "raw/"

    @property
    def reference(self) -> str:
        return self.dir_data + "reference/"

    @property
    def system(self) -> str:
        return self.dir_data + "system/"

    @property
    def temp(self) -> str:
        return self.dir_data + "temp/"

    @property
    def views(self) -> str:
        return self.dir_data + "views/"

    def _initialize(self, config: Union[dict, str, Path, None] = None):
        self.drive = DriveManager()

        if config is None:
            cfg = load_json(self.drive, self.config + "config.json")
        elif isinstance(config, dict):
            cfg = config
        else:
            cfg = load_json(self.drive, str(config))

        self.use_google_drive = cfg.get(KEY_GOOGLE_DRIVE, False)
        self.drive.set_google_drive(self.use_google_drive)

        self.dir_data = f'{self.resolve(cfg[KEY_SUB_DATA] or "arkeo")}/'

    def resolve(self, path: Union[str, Path]) -> str:
        """generic path resolution - expand user paths and join with drive root"""
        path = str(path)
        expanded_path = os.path.expanduser(path)
        if expanded_path.find(self.default) < 0:
            return str(Path(self.default) / expanded_path)
        else:
            return str(expanded_path)
