import os

from common import (
    ExitCode,
    Fore,
    exec_command,
    exit_message,
    get_env_variable,
    get_env_variable_required,
    print_message,
    set_env_variable,
)
from common.sonar_helper import SonarHelper, SonarScannerType
from src.interface.project import ProjectInterface


class DotnetProjectInterface(ProjectInterface):
    def __init__(self):
        super().__init__()
        self.publish_type = ""
        self.ci_project_dir = get_env_variable_required("CI_PROJECT_DIR")

    def compile(self):
        if not self._dotnet_buildable():
            return

        print_message(f"Compilando projeto v{self.version}...")
        self._exec_dotnet_command(f"build -c release -p:version={self.version}")

        print_message("Compilação finalizada com sucesso.", Fore.GREEN)

    def unit_test(self):
        if not self._dotnet_buildable():
            return

        self._exec_dotnet_command(
            'test -c release --collect:"XPlat Code Coverage" '
            "--results-directory results "
            "-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover"
        )

    def sonar_scanner(self):
        self._dotnet_buildable()

        sonar_helper = SonarHelper(
            sonar_scanner_type=SonarScannerType.DOTNET,
            skip_build=self.buildable_project.skip_build(),
        )
        sonar_helper.scanner_analyze()

    def package(self):
        pass

    def _configure_nuget(self):
        nexus_username = get_env_variable_required("NEXUS_USERNAME")
        nexus_password = get_env_variable_required("NEXUS_PASSWORD")

        self._exec_dotnet_command(
            "nuget add source https://nexus.senior.com.br/repository/nuget/index.json "
            f"--name nexus-nuget --username {nexus_username} --password {nexus_password} --store-password-in-clear-text"
        )

    @staticmethod
    def _exec_dotnet_command(command):

        command_result_dotnet = exec_command(f"dotnet {command}")

        if command_result_dotnet.exit_code == ExitCode.ERROR:
            exit_message("Dotnet command failed. Exiting...")

    def _publish(self):
        if not self.publish_type:
            return

        print_message(f"Gerando artefatos com 'dotnet {self.publish_type}'...")
        self._exec_dotnet_command(
            f"{self.publish_type} -c release "
            f"-p:OutputPath={self.ci_project_dir}/output/ "
            f"-p:version={self.version} "
            f"-p:CopyLocalLockFileAssemblies=true"
        )

    def _dotnet_buildable(self):
        if self.buildable_project.skip_build():
            return False
        set_env_variable(
            "NUGET_PACKAGES", f"{get_env_variable('CI_PROJECT_DIR')}/.nuget/packages"
        )
        self._configure_nuget()
        return True
