# 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/>.

"""
Module for parsing and comparing Gentoo packages (ebuild)

Currently the ebuild are based upon find within `/usr/portage` and are
manipulated as:
sed 's,/usr/portage/([^/]*)/.*/([^/]*).ebuild$,\1/\2,'

Meaning the corresponding name will be:
x11-plugins/wmix-3.5

The version generated by our generator will be delivered via name and version.

The version of the program is program specific hence we could just use Version
of pep440 to guess immediately.
"""

import logging
from dataclasses import dataclass

from .package import Package, PackageComparison

logger = logging.getLogger(__name__)


@dataclass(eq=False)
class EBuildPackage(Package):
    """Represents a .ebuild based package"""

    def compare(self, other: Package) -> PackageComparison:
        if self.name != other.name:
            return PackageComparison.NOT_COMPARABLE

        if self.full_version == other.full_version:
            return PackageComparison.EQUAL

        return self.version_compare(self.full_version, other.full_version)

    @staticmethod
    def from_full_name(full_name: str):
        if not full_name:
            return None
        base_name = (
            full_name[full_name.index("/") + 1 :]
            if "/" in full_name
            else full_name
        )
        if not base_name:
            return None
        d_index = base_name.index("-") if "-" in base_name else len(base_name)
        full_version = base_name[d_index + 1 :]
        if not full_version:
            return None
        return EBuildPackage(
            name=full_name[: len(full_name) - len(base_name[d_index:])],
            full_name=full_name,
            full_version=full_version,
        )

    @staticmethod
    def from_name_and_full_version(name: str, full_version: str):
        if not name or not full_version:
            return None
        name = name.strip()
        full_version = full_version.strip()
        return EBuildPackage(
            name=name,
            full_name=f"{name}-{full_version}",
            full_version=full_version,
        )
