"""Config file parser."""
import pathlib
from typing import Optional

from yaml import safe_load

from .const import DEFAULT_CONF_FILE_PATH, DEFAULT_CONFIG_DATA


class Config:
    """Config file parser class implementation."""

    def __init__(self, config_file_path: Optional[pathlib.Path] = None):
        """Initialize the Config class.

        Args:
            config_file_path (Optional[pathlib.Path]): config file path.
                Defaults to None.

        Raises:
            FileNotFoundError: if user defined file path doesn't exist.
        """
        if config_file_path:
            user_defined_path = True
        else:
            user_defined_path = False
        self.config_file_path = config_file_path or self._find_default_path()
        if self.config_file_path.exists():
            with open(self.config_file_path.absolute(), "r") as cf:
                self.data = safe_load(cf)
        elif user_defined_path:
            raise FileNotFoundError(
                "Config file '{}' not found.".format(self.config_file_path.absolute())
            )
        else:
            self.data = DEFAULT_CONFIG_DATA

    @staticmethod
    def _find_default_path() -> pathlib.Path:
        """Find config file based on default path.

        Returns:
            pathlib.Path: default config file path.
        """
        for candidate_file in DEFAULT_CONF_FILE_PATH:
            conf_path = pathlib.Path(candidate_file).expanduser()
            if conf_path.exists():
                return conf_path
        return pathlib.Path(DEFAULT_CONF_FILE_PATH[0]).expanduser()
