# Copyright (C) 2021-2022 Greenbone Networks GmbH
#
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from typing import Dict, List

from .packages.package import Package, PackageAdvisory


class Vulnerability:
    """Represents a vulnerable package on a host"""

    vulnerability: Dict[Package, List[PackageAdvisory]]

    def __init__(self) -> None:
        self.vulnerability = {}

    def add(self, package: Package, fixed: PackageAdvisory) -> None:
        """Adds a detection to a package. A detection indicates a vulnerable
        package. Multiple detections indicates a version range."""
        if package not in self.vulnerability:
            self.vulnerability[package] = list()
        self.vulnerability[package].append(fixed)

    def combine(self, vul: "Vulnerability"):
        self.vulnerability = {**self.vulnerability, **vul.vulnerability}

    def get(self) -> Dict[Package, List[PackageAdvisory]]:
        return self.vulnerability


class Vulnerabilities:
    """Adds a vulnerable package corresponding to a given OID. It is
    possible, that there are multiple vulnerable packages for a single
    OID"""

    vulnerabilities: Dict[str, Vulnerability]

    def __init__(self) -> None:
        self.vulnerabilities = dict()

    def __len__(self) -> int:
        return len(self.vulnerabilities)

    def add(self, oid: str, vul: Vulnerability):
        if not oid in self.vulnerabilities:
            self.vulnerabilities[oid] = vul
            return

        self.vulnerabilities[oid].combine(vul)

    def get(self) -> Dict[str, Vulnerability]:
        return self.vulnerabilities
