import collections
import logging
import shelve
from datetime import datetime
from threading import RLock
import pickle
from mainserver.user_manager import UserManager
from KL.status_codes import StatusCodes
from KL.types import *
from KL.application_protocol import NodeClass, ReferenceDescription, AddNodesResult, AddReferencesItem, \
    NodeAttributesMask, BrowseResult
from KL.attribute_ids import AttributeIds
from KL.constants import ObjectIds


class AttributeValue(object):

    def __init__(self, value):
        self.value = value
        self.value_callback = None
        self.datachange_callbacks = {}

    def __str__(self):
        return "AttributeValue({0})".format(self.value)

    __repr__ = __str__


def test_bit(data, offset):
    mask = 1 << offset
    return data & mask


class AttributeService(object):

    def __init__(self, aspace):
        self.logger = logging.getLogger(__name__)
        self._aspace = aspace

    def read(self, params):
        self.logger.debug("read %s", params)
        res = []
        for readvalue in params.NodesToRead:
            res.append(self._aspace.get_attribute_value(readvalue.NodeId, readvalue.AttributeId))
        return res

    def write(self, params, user=UserManager.User.Admin):
        self.logger.debug("write %s as user %s", params, user)
        res = []
        for writevalue in params.NodesToWrite:
            if user != UserManager.User.Admin:
                if writevalue.AttributeId != AttributeIds.Value:
                    res.append(StatusCode(StatusCodes.BadUserAccessDenied))
                    continue
                al = self._aspace.get_attribute_value(writevalue.NodeId, AttributeIds.AccessLevel)
                ual = self._aspace.get_attribute_value(writevalue.NodeId, AttributeIds.UserAccessLevel)
                if not test_bit(al.Value.Value, AccessLevel.CurrentWrite) or not test_bit(
                        ual.Value.Value, AccessLevel.CurrentWrite):
                    res.append(StatusCode(StatusCodes.BadUserAccessDenied))
                    continue
            res.append(self._aspace.set_attribute_value(writevalue.NodeId, writevalue.AttributeId, writevalue.Value))
        return res


class ViewService(object):

    def __init__(self, aspace):
        self.logger = logging.getLogger(__name__)
        self._aspace = aspace

    def browse(self, params):
        self.logger.debug("browse %s", params)
        res = []
        for desc in params.NodesToBrowse:
            res.append(self._browse(desc))
        return res

    def _browse(self, desc):
        res = BrowseResult()
        if desc.NodeId not in self._aspace:
            res.StatusCode = StatusCode(StatusCodes.BadNodeIdInvalid)
            return res
        node = self._aspace[desc.NodeId]
        for ref in node.references:
            if not self._is_suitable_ref(desc, ref):
                continue
            res.References.append(ref)
        return res

    def _is_suitable_ref(self, desc, ref):
        pass


class NodeData(object):

    def __init__(self, nodeid):
        self.nodeid = nodeid
        self.attributes = {}
        self.references = []
        self.call = None

    def __str__(self):
        return "NodeData(id:{0}, attrs:{1}, refs:{2})".format(self.nodeid, self.attributes, self.references)
    __repr__ = __str__


class NodeManagementService(object):

    def __init__(self, aspace):
        self.logger = logging.getLogger(__name__)
        self._aspace = aspace

    def add_nodes(self, addnodeitems, user=UserManager.User.Admin):
        results = []
        for item in addnodeitems:
            results.append(self._add_node(item, user))
        return results

    def try_add_nodes(self, addnodeitems, user=UserManager.User.Admin, check=True):
        for item in addnodeitems:
            ret = self._add_node(item, user, check=check)
            if not ret.StatusCode.is_good():
                yield item

    def _add_node(self, item, user, check=True):
        self.logger.debug("Adding node %s %s", item.RequestedNewNodeId, item.BrowseName)
        result = AddNodesResult()

        if not user == UserManager.User.Admin:
            result.StatusCode = StatusCode(StatusCodes.BadUserAccessDenied)
            return result

        if item.RequestedNewNodeId.has_null_identifier():
            # If Identifier of requested NodeId is null we generate a new NodeId using
            # the namespace of the nodeid, this is an extention of the spec to allow
            # to requests the server to generate a new nodeid in a specified namespace
            self.logger.debug("RequestedNewNodeId has null identifier, generating Identifier")
            item.RequestedNewNodeId = self._aspace.generate_nodeid(item.RequestedNewNodeId.NamespaceIndex)
        else:
            if item.RequestedNewNodeId in self._aspace:
                self.logger.warning("AddNodesItem: Requested NodeId %s already exists", item.RequestedNewNodeId)
                result.StatusCode = StatusCode(StatusCodes.BadNodeIdExists)
                return result

        if item.ParentNodeId.is_null():
            self.logger.info("add_node: while adding node %s, requested parent node is null %s %s",
                             item.RequestedNewNodeId, item.ParentNodeId, item.ParentNodeId.is_null())
            if check:
                result.StatusCode = StatusCode(StatusCodes.BadParentNodeIdInvalid)
                return result

        parentdata = self._aspace.get(item.ParentNodeId)
        if parentdata is None and not item.ParentNodeId.is_null():
            self.logger.info("add_node: while adding node %s, requested parent node %s does not exists",
                             item.RequestedNewNodeId, item.ParentNodeId)
            result.StatusCode = StatusCode(StatusCodes.BadParentNodeIdInvalid)
            return result

        nodedata = NodeData(item.RequestedNewNodeId)

        self._add_node_attributes(nodedata, item, add_timestamps=check)

        # now add our node to db
        self._aspace[nodedata.nodeid] = nodedata

        if parentdata is not None:
            self._add_ref_from_parent(nodedata, item, parentdata)
            self._add_ref_to_parent(nodedata, item, parentdata)

        # add type definition
        if item.TypeDefinition != NodeId():
            self._add_type_definition(nodedata, item)

        result.StatusCode = StatusCode()
        result.AddedNodeId = nodedata.nodeid

        return result

    def _add_node_attributes(self, nodedata, item, add_timestamps):
        # add common attrs
        if nodedata.nodeid.Identifier == 2256 or nodedata.nodeid.Identifier == 2255:
            print("Found node 2256 or 2255")
        nodedata.attributes[AttributeIds.NodeId] = AttributeValue(
            DataValue(Variant(nodedata.nodeid, VariantType.NodeId))
        )
        nodedata.attributes[AttributeIds.BrowseName] = AttributeValue(
            DataValue(Variant(item.BrowseName, VariantType.QualifiedName))
        )
        nodedata.attributes[AttributeIds.NodeClass] = AttributeValue(
            DataValue(Variant(item.NodeClass, VariantType.Int32))
        )
        # add requested attrs
        self._add_nodeattributes(item.NodeAttributes, nodedata, add_timestamps)

    def _add_unique_reference(self, nodedata, desc):
        for r in nodedata.references:
            if r.ReferenceTypeId == desc.ReferenceTypeId and r.NodeId == desc.NodeId:
                if r.IsForward != desc.IsForward:
                    self.logger.error("Cannot add conflicting reference %s ", str(desc))
                    return StatusCode(StatusCodes.BadReferenceNotAllowed)
                break  # ref already exists
        else:
            nodedata.references.append(desc)
        return StatusCode()

    def _add_ref_from_parent(self, nodedata, item, parentdata):
        desc = ReferenceDescription()
        desc.ReferenceTypeId = item.ReferenceTypeId
        desc.NodeId = nodedata.nodeid
        desc.NodeClass = item.NodeClass
        desc.BrowseName = item.BrowseName
        desc.DisplayName = item.NodeAttributes.DisplayName
        desc.TypeDefinition = item.TypeDefinition
        desc.IsForward = True
        self._add_unique_reference(parentdata, desc)

    def _add_ref_to_parent(self, nodedata, item, parentdata):
        addref = AddReferencesItem()
        addref.ReferenceTypeId = item.ReferenceTypeId
        addref.SourceNodeId = nodedata.nodeid
        addref.TargetNodeId = item.ParentNodeId
        addref.TargetNodeClass = parentdata.attributes[AttributeIds.NodeClass].value.Value.Value
        addref.IsForward = False
        self._add_reference_no_check(nodedata, addref)

    def _add_type_definition(self, nodedata, item):
        addref = AddReferencesItem()
        addref.SourceNodeId = nodedata.nodeid
        addref.IsForward = True
        addref.ReferenceTypeId = NodeId(ObjectIds.HasTypeDefinition)
        addref.TargetNodeId = item.TypeDefinition
        addref.TargetNodeClass = NodeClass.DataType
        self._add_reference_no_check(nodedata, addref)

    def delete_nodes(self, deletenodeitems, user=UserManager.User.Admin):
        results = []
        for item in deletenodeitems.NodesToDelete:
            results.append(self._delete_node(item, user))
        return results

    def _delete_node(self, item, user):
        if user != UserManager.User.Admin:
            return StatusCode(StatusCodes.BadUserAccessDenied)

        if item.NodeId not in self._aspace:
            self.logger.warning("DeleteNodesItem: NodeId %s does not exists", item.NodeId)
            return StatusCode(StatusCodes.BadNodeIdUnknown)

        if item.DeleteTargetReferences:
            for elem in self._aspace.keys():
                for rdesc in self._aspace[elem].references[:]:
                    if rdesc.NodeId == item.NodeId:
                        self._aspace[elem].references.remove(rdesc)

        self._delete_node_callbacks(self._aspace[item.NodeId])

        del (self._aspace[item.NodeId])

        return StatusCode()

    def _delete_node_callbacks(self, nodedata):
        if AttributeIds.Value in nodedata.attributes:
            for handle, callback in list(nodedata.attributes[AttributeIds.Value].datachange_callbacks.items()):
                try:
                    callback(handle, None, StatusCode(StatusCodes.BadNodeIdUnknown))
                    self._aspace.delete_datachange_callback(handle)
                except Exception as ex:
                    self.logger.exception("Error calling delete node callback callback %s, %s, %s", nodedata,
                                          AttributeIds.Value, ex)

    def add_references(self, refs, user=UserManager.User.Admin):
        result = []
        for ref in refs:
            result.append(self._add_reference(ref, user))
        return result

    def try_add_references(self, refs, user=UserManager.User.Admin):
        for ref in refs:
            if not self._add_reference(ref, user).is_good():
                yield ref

    def _add_reference(self, addref, user):
        sourcedata = self._aspace.get(addref.SourceNodeId)
        if sourcedata is None:
            return StatusCode(StatusCodes.BadSourceNodeIdInvalid)
        if addref.TargetNodeId not in self._aspace:
            return StatusCode(StatusCodes.BadTargetNodeIdInvalid)
        if user != UserManager.User.Admin:
            return StatusCode(StatusCodes.BadUserAccessDenied)
        return self._add_reference_no_check(sourcedata, addref)

    def _add_reference_no_check(self, sourcedata, addref):
        rdesc = ReferenceDescription()
        rdesc.ReferenceTypeId = addref.ReferenceTypeId
        rdesc.IsForward = addref.IsForward
        rdesc.NodeId = addref.TargetNodeId
        if addref.TargetNodeClass == NodeClass.Unspecified:
            rdesc.NodeClass = self._aspace.get_attribute_value(addref.TargetNodeId, AttributeIds.NodeClass).Value.Value
        else:
            rdesc.NodeClass = addref.TargetNodeClass
        bname = self._aspace.get_attribute_value(addref.TargetNodeId, AttributeIds.BrowseName).Value.Value
        if bname:
            rdesc.BrowseName = bname
        dname = self._aspace.get_attribute_value(addref.TargetNodeId, AttributeIds.DisplayName).Value.Value
        if dname:
            rdesc.DisplayName = dname
        return self._add_unique_reference(sourcedata, rdesc)

    def delete_references(self, refs, user=UserManager.User.Admin):
        result = []
        for ref in refs:
            result.append(self._delete_reference(ref, user))
        return result

    def _delete_unique_reference(self, item, invert=False):
        if invert:
            source, target, forward = item.TargetNodeId, item.SourceNodeId, not item.IsForward
        else:
            source, target, forward = item.SourceNodeId, item.TargetNodeId, item.IsForward
        for rdesc in self._aspace[source].references:
            if rdesc.NodeId == target and rdesc.ReferenceTypeId == item.ReferenceTypeId:
                if rdesc.IsForward == forward:
                    self._aspace[source].references.remove(rdesc)
                    return StatusCode()
        return StatusCode(StatusCodes.BadNotFound)

    def _delete_reference(self, item, user):
        if item.SourceNodeId not in self._aspace:
            return StatusCode(StatusCodes.BadSourceNodeIdInvalid)
        if item.TargetNodeId not in self._aspace:
            return StatusCode(StatusCodes.BadTargetNodeIdInvalid)
        if item.ReferenceTypeId not in self._aspace:
            return StatusCode(StatusCodes.BadReferenceTypeIdInvalid)
        if user != UserManager.User.Admin:
            return StatusCode(StatusCodes.BadUserAccessDenied)

        if item.DeleteBidirectional:
            self._delete_unique_reference(item, True)
        return self._delete_unique_reference(item)

    def _add_node_attr(self, item, nodedata, name, vtype=None, add_timestamps=False):
        if name == 'Value' and (nodedata.nodeid.Identifier == 2255 or nodedata.nodeid.Identifier == 11705 or
                                nodedata.nodeid.Identifier == 2254 or nodedata.nodeid.Identifier == 2259 or
                                nodedata.nodeid.Identifier == 2257 or nodedata.nodeid.Identifier == 2258 or
                                nodedata.nodeid.Identifier == 2256):
            item.SpecifiedAttributes = 4002419
        if item.SpecifiedAttributes & getattr(NodeAttributesMask, name):
            dv = DataValue(Variant(getattr(item, name), vtype))
            if add_timestamps:
                # dv.ServerTimestamp = datetime.utcnow()  # Disabled until someone explains us it should be there
                dv.SourceTimestamp = datetime.utcnow()
            nodedata.attributes[getattr(AttributeIds, name)] = AttributeValue(dv)

    def _add_nodeattributes(self, item, nodedata, add_timestamps):
        self._add_node_attr(item, nodedata, "AccessLevel", VariantType.Byte)
        self._add_node_attr(item, nodedata, "ArrayDimensions", VariantType.UInt32)
        self._add_node_attr(item, nodedata, "BrowseName", VariantType.QualifiedName)
        self._add_node_attr(item, nodedata, "ContainsNoLoops", VariantType.Boolean)
        self._add_node_attr(item, nodedata, "DataType", VariantType.NodeId)
        self._add_node_attr(item, nodedata, "Description", VariantType.LocalizedText)
        self._add_node_attr(item, nodedata, "DisplayName", VariantType.LocalizedText)
        self._add_node_attr(item, nodedata, "EventNotifier", VariantType.Byte)
        self._add_node_attr(item, nodedata, "Executable", VariantType.Boolean)
        self._add_node_attr(item, nodedata, "Historizing", VariantType.Boolean)
        self._add_node_attr(item, nodedata, "InverseName", VariantType.LocalizedText)
        self._add_node_attr(item, nodedata, "IsAbstract", VariantType.Boolean)
        self._add_node_attr(item, nodedata, "MinimumSamplingInterval", VariantType.Double)
        self._add_node_attr(item, nodedata, "NodeClass", VariantType.Int32)
        self._add_node_attr(item, nodedata, "NodeId", VariantType.NodeId)
        self._add_node_attr(item, nodedata, "Symmetric", VariantType.Boolean)
        self._add_node_attr(item, nodedata, "UserAccessLevel", VariantType.Byte)
        self._add_node_attr(item, nodedata, "UserExecutable", VariantType.Boolean)
        self._add_node_attr(item, nodedata, "UserWriteMask", VariantType.Byte)
        self._add_node_attr(item, nodedata, "ValueRank", VariantType.Int32)
        self._add_node_attr(item, nodedata, "WriteMask", VariantType.UInt32)
        self._add_node_attr(item, nodedata, "UserWriteMask", VariantType.UInt32)
        self._add_node_attr(item, nodedata, "Value", add_timestamps=add_timestamps)


class MethodService(object):

    def __init__(self, aspace):
        self.logger = logging.getLogger(__name__)
        self._aspace = aspace


class AddressSpace(object):
    """
    The address space object stores all the nodes of the OPC-UA server
    and helper methods.
    The methods are thread safe
    """

    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self._nodes = {}
        self._lock = RLock()  # FIXME: should use multiple reader, one writter pattern
        self._datachange_callback_counter = 200
        self._handle_to_attribute_map = {}
        self._default_idx = 2
        self._nodeid_counter = {0: 20000, 1: 2000}

    def __getitem__(self, nodeid):
        with self._lock:
            return self._nodes.__getitem__(nodeid)

    def get(self, nodeid):
        with self._lock:
            return self._nodes.get(nodeid, None)

    def __setitem__(self, nodeid, value):
        with self._lock:
            return self._nodes.__setitem__(nodeid, value)

    def __contains__(self, nodeid):
        with self._lock:
            return self._nodes.__contains__(nodeid)

    def __delitem__(self, nodeid):
        with self._lock:
            self._nodes.__delitem__(nodeid)

    def generate_nodeid(self, idx=None):
        if idx is None:
            idx = self._default_idx
        if idx in self._nodeid_counter:
            self._nodeid_counter[idx] += 1
        else:
            # get the biggest identifier number from the existed nodes in address space
            identifier_list = sorted([nodeid.Identifier for nodeid in self._nodes.keys()
                                      if nodeid.NamespaceIndex == idx and nodeid.NodeIdType
                                      in (NodeIdType.Numeric, NodeIdType.TwoByte, NodeIdType.FourByte)])
            if identifier_list:
                self._nodeid_counter[idx] = identifier_list[-1]
            else:
                self._nodeid_counter[idx] = 1
        nodeid = NodeId(self._nodeid_counter[idx], idx)
        with self._lock:  # OK since reentrant lock
            while True:
                if nodeid in self._nodes:
                    nodeid = self.generate_nodeid(idx)
                else:
                    return nodeid

    def load_aspace_shelf(self, path):
        """
        Load the standard address space nodes from a python shelve via LazyLoadingDict as needed.
        The dump() method can no longer be used if the address space is being loaded from a shelf

        Note: Intended for slow devices, such as Raspberry Pi, to greatly improve start up time
        """

        class LazyLoadingDict(collections.MutableMapping):
            """
            Special dict that only loads nodes as they are accessed. If a node is accessed it gets copied from the
            shelve to the cache dict. All user nodes are saved in the cache ONLY. Saving data back to the shelf
            is currently NOT supported
            """

            def __init__(self, source):
                self.source = source  # python shelf
                self.cache = {}  # internal dict

            def __getitem__(self, key):
                # try to get the item (node) from the cache, if it isn't there get it from the shelf
                try:
                    return self.cache[key]
                except KeyError:
                    node = self.cache[key] = self.source[key.to_string()]
                    return node

            def __setitem__(self, key, value):
                # add a new item to the cache; if this item is in the shelf it is not updated
                self.cache[key] = value

            def __contains__(self, key):
                return key in self.cache or key.to_string() in self.source

            def __delitem__(self, key):
                # only deleting items from the cache is allowed
                del self.cache[key]

            def __iter__(self):
                # only the cache can be iterated over
                return iter(self.cache.keys())

            def __len__(self):
                # only returns the length of items in the cache, not unaccessed items in the shelf
                return len(self.cache)

        self._nodes = LazyLoadingDict(shelve.open(path, "r"))

    def make_aspace_shelf(self, path):
        """
        Make a shelf for containing the nodes from the standard address space; this is typically only done on first
        start of the server. Subsequent server starts will load the shelf, nodes are then moved to a cache
        by the LazyLoadingDict class when they are accessed. Saving data back to the shelf
        is currently NOT supported, it is only used for the default OPC UA standard address space

        Note: Intended for slow devices, such as Raspberry Pi, to greatly improve start up time
        """
        s = shelve.open(path, "n", protocol=pickle.HIGHEST_PROTOCOL)
        for nodeid, ndata in self._nodes.items():
            s[nodeid.to_string()] = ndata
        s.close()

    def get_attribute_value(self, nodeid, attr):
        with self._lock:
            self.logger.debug("get attr val: %s %s", nodeid, attr)
            if nodeid not in self._nodes:
                dv = DataValue()
                dv.StatusCode = StatusCode(StatusCodes.BadNodeIdUnknown)
                return dv
            node = self._nodes[nodeid]
            if attr not in node.attributes:
                self.logger.warning("Tried to read attribute '%s' in %s, but the attribute is missing", attr, nodeid)
                dv = DataValue()
                dv.StatusCode = StatusCode(StatusCodes.BadAttributeIdInvalid)
                return dv
            attval = node.attributes[attr]
            if attval.value_callback:
                return attval.value_callback()
            return attval.value

    def set_attribute_value(self, nodeid, attr, value):
        with self._lock:
            self.logger.debug("set attr val: %s %s %s", nodeid, attr, value)
            node = self._nodes.get(nodeid, None)
            if node is None:
                return StatusCode(StatusCodes.BadNodeIdUnknown)
            attval = node.attributes.get(attr, None)
            if attval is None:
                self.logger.warning("Tried to write attribute '%s' in %s, but the attribute is missing", attr, nodeid)
                return StatusCode(StatusCodes.BadAttributeIdInvalid)

            old = attval.value
            attval.value = value
            cbs = []
            if old.Value != value.Value:  # only send call callback when a value change has happend
                cbs = list(attval.datachange_callbacks.items())

        for k, v in cbs:
            try:
                v(k, value)
            except Exception as ex:
                self.logger.exception("Error calling datachange callback %s, %s, %s", k, v, ex)

        return StatusCode()
