"""Scripts for DotNet CI/CD"""

import getopt
import sys

from colorama import Fore

from common import (
    ExitCode,
    exec_command,
    exit_message,
    get_env_variable,
    get_last_version,
    get_version,
    is_semver,
    print_message,
)
from common.extensions import Extensions
from common.sonar_helper import SonarHelper, SonarScannerType
from common.validations.buildable import BuildableProject
from common.validations.changelog import ValidateChangelog
from common.validations.issues import check_and_validate_issues


class BaseDotNetCI(object):
    def __init__(self, argv):
        self.buildable_project = BuildableProject()

        try:
            self.opts, self.args = getopt.getopt(argv, "vpr:g:x")
        except getopt.GetoptError as err:
            exit_message(err)

        self._validade_options()

        print_message(
            "Atenção: Este script será descontinuado em breve."
            "Por favor, atualize o CI utilizando o Bastion."
            "Caso não seja possível, entre em contato com o time de DevSecOps.",
            Fore.YELLOW,
        )

    def _validade_options(self):
        len_opts = len(self.opts)

        if len_opts == 0:
            exit_message("É preciso informar as opções.")

    def validation(self):
        check_and_validate_issues()

        print_message("Executando validação de código")

        extensions = Extensions()
        extensions.before_build()

        validate_changelog = ValidateChangelog()
        validate_changelog.validate()

        version = self.get_version()
        self.compile(version)

        extensions.after_build()

    def compile(self, version: str):
        """Serve de interface para chamar a publicação de cada classe filha"""

    @staticmethod
    def get_version():
        """Checks the project version, changing it to .NET standards"""

        project_version = get_version()

        if not is_semver(project_version):
            ci_commit_ref_slug = get_env_variable("CI_COMMIT_REF_SLUG")

            last_version = get_last_version()

            if not last_version:
                last_version = "0.0.0"

            project_version = f"{last_version}-{ci_commit_ref_slug}-SNAPSHOT"

        return project_version

    @staticmethod
    def configure_nuget():
        print_message("Configurando nuget sources")

        maven_user = get_env_variable("MAVEN_USERNAME")
        maven_password = get_env_variable("MAVEN_PASSWORD")

        exec_command(
            f"dotnet nuget add source "
            "https://maven.senior.com.br/artifactory/nuget/index.json "
            f"--name Artifactory --username {maven_user} --password {maven_password} --store-password-in-clear-text"
        )

    @staticmethod
    def release(versioning_release: str):
        check_and_validate_issues()

        exec_command(f"bash senior-ci/ci/ci.sh -r {versioning_release}")

    def run_sonar(self):
        check_and_validate_issues()

        if not self.buildable_project.skip_build():
            self.configure_nuget()

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

        sonar_helper.scanner_analyze()
