from common import (
    get_env_variable,
    get_env_variable_required,
    is_path_exist,
    regex_path_exists,
)
from common.graphql_client import GraphqlClient

NEEDED_FILES = [
    "pom.xml",
    "package.json",
    "pubspec.yaml",
    "go.mod",
    "*.sln",
    "*.csproj",
    "pyproject.toml",
    "requirements.txt",
]


class BuildableProject(object):
    def __init__(self) -> None:
        self.client_graphql = GraphqlClient()

    def skip_build(self):
        if not self._needed_file_exists() and (
            (
                get_env_variable("CI_COMMIT_BRANCH") == "develop"
                and not self._develop_exists_on_sonar()
            )
            or (
                get_env_variable("CI_COMMIT_BRANCH") == "master"
                and not self._master_exists_on_sonar()
            )
        ):
            return f"Skip build porque nenhum dos seguintes arquivos foi encontrado: {', '.join(NEEDED_FILES)}"
        return False

    @staticmethod
    def _needed_file_exists():
        for file in NEEDED_FILES:
            if is_path_exist(file) or regex_path_exists(file):
                return True

        return False

    def _develop_exists_on_sonar(self):
        query = """
            query ($projectKey: String!, $branchName: String!) {
                branchExistsOnSonar(projectKey: $projectKey, branchName: $branchName) {
                    exists
                }
            }
        """

        params = {
            "projectKey": get_env_variable_required("CI_PROJECT_PATH_SLUG"),
            "branchName": "develop",
        }

        request = self.client_graphql.call(query, params)

        return request["branchExistsOnSonar"]["exists"]

    def _master_exists_on_sonar(self):
        query = """
            query ($projectKey: String!, $branchName: String!) {
                branchExistsOnSonar(projectKey: $projectKey, branchName: $branchName) {
                    exists
                }
            }
        """

        params = {
            "projectKey": get_env_variable_required("CI_PROJECT_PATH_SLUG"),
            "branchName": "master",
        }

        request = self.client_graphql.call(query, params)

        return request["branchExistsOnSonar"]["exists"]
