import json
import pathlib

from .user import user
from .user import user_factory
from .user import user_builder
from .exception import config_exception
from .users_collection import users_collection

class users_saver:
    """
    This class is responsible for saving and storing user config file.
    """

    def __init__(self, collection: users_collection) -> None:
        """
        This initialize class, by set users collection.
        
        Parameters:
            collection (users_collection): This is collection of users to save
        """

        self.__collection = collection
        self.__where = None
    
    @property
    def users(self) -> list:
        """ This return list of users in setup collection. """

        return [ count.flat for count in self.__collection.all ]

    def drop(self, where: pathlib.Path) -> object:
        """
        This drop config file, when it already exists. If given path is 
        directory, raise config exception. Path is been saving to use it 
        in save. When first call to drop, save after it could be call without
        parameters.

        Parameters:
            where (pathlib.Path): Place where config file had been
        
        Returns:
            (users_saver): Object instance itself
        """

        self.__where = where

        if not where.exists():
            return self

        if where.is_dir():
            content = "Can not remove users config, because target \""
            content = content + str(where) + "\" is file."

            raise config_exception(content)
        
        where.unlink()
        return self
    
    def save(self, where: pathlib.Path | None = None) -> object:
        """
        This function save users collection as users config file. When place
        is not provided, trying to load it from previous place, in drop. When
        config file already exists, raise config.

        Parameters:
            where (pathlib.Path | None): Place to save config (default: None)

        Returns:
            (users_saver): Instance of this class itself
        """

        if where is None:
            where = self.__where

        if where is None:
            raise RuntimeError("Where is not set.")

        if where.exists():
            content = "Config file \"" + str(where) + "\" already exists."
            
            raise config_exception(content)

        with where.open("w") as handle:
            handle.write(json.dumps(self.users))

        return self
