import json
import pathlib

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

class users_loader:
    """
    This is responsible for loading users from the config file. It create 
    collection with all of the users from the file.
    """

    def __init__(self, target: pathlib.Path) -> None:
        """
        This create new loader. It get file as pathlib location, to open it
        and load. File must be a JSON, with array of the users object.

        Parameters:
            target (Path): Path to JSON file with users
        """

        self.__collection = users_collection()
        
        if not target.is_file():
            error = "Users config file \"" + str(target) + "\" not exists."
            raise config_exception(error)

        with target.open() as handler:
            self.__parse(json.loads(handler.read()))

    def __parse(self, target: list) -> None:
        """
        This parse array from JSON, as users.

        Parameters:
            target (list): List of users dicts from JSON
        """

        for count in target:
            self.collection.add(user_builder(count).result)

    @property
    def collection(self) -> users_collection:
        """ Collections with the users. """

        return self.__collection
