"""
Models for users.

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

import subprocess
import re
import copy

from rookeries import database as db

PASSWORD_HASHED_REGEX = re.compile(r'^\$rpbkdf2')


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: Proper tests.
        password = kwargs.get('password')
        if not password:
            self.password = None
        elif PASSWORD_HASHED_REGEX.match(password):
            self.password = password
        else:
            self.password = User.gen_pass_hash(password)

    @staticmethod
    def doc_type():
        return 'user'

    @staticmethod
    def gen_pass_hash(password: str):
        results = subprocess.run(
            ['target/debug/rookeries', 'password', password],
            stdout=subprocess.PIPE
        )
        return str(results.stdout, encoding='utf-8').strip()

    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)
