# SPDX-FileCopyrightText: 2021-2024 Greenbone AG
#
# SPDX-License-Identifier: AGPL-3.0-or-later

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 oid not in self.vulnerabilities:
            self.vulnerabilities[oid] = vul
            return

        self.vulnerabilities[oid].combine(vul)

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