# Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.

import stix
import stix.bindings.exploit_target as exploit_target_binding
from stix.common import StructuredText


class Weakness(stix.Entity):
    """Implementation of STIX ``Weakness``.

    Args:
        cwe_id(optional): Common Weakness Enumeration value as a string
        description (optional): A string description.

    """
    _binding = exploit_target_binding
    _binding_class = _binding.WeaknessType
    _namespace = "http://stix.mitre.org/ExploitTarget-1"

    def __init__(self, description=None, cwe_id=None):
        self.description = description
        self.cwe_id = cwe_id

    @property
    def cwe_id(self):
        """
        Common Weakness Enumeration value as a string
        """
        return self._cwe_id

    @cwe_id.setter
    def cwe_id(self, value):
        self._cwe_id = value

    @property
    def description(self):
        """The ``description`` property for this :class:`Weakness`.

        Default Value: ``None``

        Note:
            If set to a value that is not an instance of
            :class:`stix.common.structured_text.StructuredText`, an attempt to
            will be made to convert the value into an instance of
            :class:`stix.common.structured_text.StructuredText`.

        Returns:
            An instance of
            :class:`stix.common.structured_text.StructuredText`

        """
        return self._description

    @description.setter
    def description(self, value):
        self._set_var(StructuredText, description=value)

    def to_obj(self, return_obj=None, ns_info=None):
        super(Weakness, self).to_obj(return_obj=return_obj, ns_info=ns_info)

        if not return_obj:
            return_obj = self._binding_class()

        if self.description:
            return_obj.Description = self.description.to_obj(ns_info=ns_info)
        return_obj.CWE_ID = self.cwe_id

        return return_obj

    @classmethod
    def from_obj(cls, obj, return_obj=None):
        if not obj:
            return None
        if not return_obj:
            return_obj = cls()

        return_obj.description = StructuredText.from_obj(obj.Description)
        return_obj.cwe_id = obj.CWE_ID

        return return_obj

    def to_dict(self):
        return super(Weakness, self).to_dict()

    @classmethod
    def from_dict(cls, dict_repr, return_obj=None):
        if not dict_repr:
            return None
        if not return_obj:
            return_obj = cls()

        return_obj.description = StructuredText.from_dict(dict_repr.get('description'))
        return_obj.cwe_id = dict_repr.get('cwe_id')

        return return_obj


class _Weaknesses(stix.TypedList):
    _contained_type = Weakness
