"""
ebuild module for version_utils

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 generater 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 packaging.version import Version

from .package import Package, PackageComparision


logger = logging.getLogger(__name__)


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

    def _compare(self, other: Package) -> PackageComparision:
        # we don't want to deal with LegacyVersion
        a_version = Version(self.full_version)
        b_version = Version(other.full_version)

        if self.name != other.name:
            return PackageComparision.NOT_COMPARABLE

        if a_version == b_version:
            return PackageComparision.EQUAL

        return (
            PackageComparision.A_NEWER
            if a_version > b_version
            else PackageComparision.B_NEWER
        )

    @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,
        )
