# -*- coding: utf-8 -*-
#
#   DIMP : Decentralized Instant Messaging Protocol
#
#                                Written in 2019 by Moky <albert.moky@gmail.com>
#
# ==============================================================================
# MIT License
#
# Copyright (c) 2019 Albert Moky
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ==============================================================================

import weakref
from abc import abstractmethod
from typing import Optional

from mkm import ID, Meta, Document


class EntityDataSource:
    """This interface is for getting information for entity(user/group)

        Entity Data Source
        ~~~~~~~~~~~~~~~~~~

        1. meta for user, which is generated by the user's private key
        2. meta for group, which is generated by the founder's private key
        3. meta key, which can verify message sent by this user(or group founder)
        4. visa key, which can encrypt message for the receiver(user)
    """

    @abstractmethod
    def meta(self, identifier: ID) -> Optional[Meta]:
        """
        Get meta for entity ID

        :param identifier: entity ID
        :return:           Meta
        """
        raise NotImplemented

    @abstractmethod
    def document(self, identifier: ID, doc_type: Optional[str]='*') -> Optional[Document]:
        """
        Get document for entity ID

        :param identifier: entity ID
        :param doc_type:   document type
        :return:           Document
        """
        raise NotImplemented


class Entity:
    """Base class of User and Group, ...

        Entity (User/Group)
        ~~~~~~~~~~~~~~~~~~~

            properties:
                identifier - entity ID
                type       - entity type
                meta       - meta for entity ID
                document   - visa for user, or bulletin for group
    """

    def __init__(self, identifier: ID):
        """
        Create Entity with ID

        :param identifier: User/Group ID
        """
        super().__init__()
        self.__identifier: ID = identifier
        self.__delegate: weakref.ReferenceType = None

    def __str__(self):
        clazz = self.__class__.__name__
        return '<%s|%s %s/>' % (clazz, self.type, self.identifier)

    def __eq__(self, other) -> bool:
        if super().__eq__(other):
            return True
        elif isinstance(other, Entity):
            return self.__identifier == other.identifier

    @property
    def delegate(self) -> Optional[EntityDataSource]:
        if self.__delegate is not None:
            return self.__delegate()

    @delegate.setter
    def delegate(self, value: EntityDataSource):
        self.__delegate = weakref.ref(value)

    @property
    def identifier(self) -> ID:
        return self.__identifier

    @property
    def type(self) -> int:
        """ Entity type """
        return self.__identifier.type

    @property
    def meta(self) -> Meta:
        assert isinstance(self.delegate, EntityDataSource), 'entity delegate error: %s' % self.delegate
        return self.delegate.meta(identifier=self.identifier)

    def document(self, doc_type: Optional[str]='*') -> Optional[Document]:
        assert isinstance(self.delegate, EntityDataSource), 'entity delegate error: %s' % self.delegate
        return self.delegate.document(identifier=self.identifier, doc_type=doc_type)
