"""
Models for users.

:copyright: Copyright 2013-2017, Dorian Pula <dorian.pula@amber-penguin-software.ca>
:license: AGPL v3+
"""

import copy

from werkzeug import security

from rookeries import database as db


class User(db.DatabaseModel):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.username = kwargs.get('username')
        self.full_name = kwargs.get('fullName')
        # TODO: Include a way to check parts of a profile
        self.profile = kwargs.get('profile', {})
        # TODO: Know when to hash and when to not...
        password = kwargs.get('password')
        if password:
            # TODO: Also determine when to hash to avoid multiple hashing.
            self.password = security.generate_password_hash(password)
        else:
            self.password = None

    @staticmethod
    def doc_type():
        return 'user'

    def _json_repr(self) -> dict:
        # TODO: Consider creating some sort of json template and mapper.
        return {
            'username': self.username,
            'fullName': self.full_name,
            'profile': {
                'email': self.profile.get('email'),
            },
        }

    def to_api_json(self):
        # TODO: Figure out how to get a user self link....
        return copy.deepcopy(self._json_repr())

    def to_db_json(self):
        db_json = copy.deepcopy(self._json_repr())
        db_json['password'] = self.password
        return self.attach_db_metadata(db_json)
