from datetime import datetime, timedelta

from common import get_env_variable, get_env_variable_required
from common.graphql_client import GraphqlClient

from .custom_issue import CustomIssue


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

    def check(self):
        """Check if project path and project name are the same."""

        query = """
            query ($projectId: Int!, $branch: String!, $projectType: ProjectTypeEnum!) {
                checkProjectPath(projectId: $projectId, branch: $branch, projectType: $projectType) {
                    success
                    reason
                }
            }
        """

        params = {
            "projectId": int(get_env_variable_required("CI_PROJECT_ID")),
            "branch": get_env_variable_required("CI_COMMIT_REF_NAME"),
            "projectType": get_env_variable_required("SCI_PROJECT_TYPE"),
        }

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

        output = CheckProjectPathOutput(result["checkProjectPath"])

        return output


class CheckProjectPathOutput(object):
    def __init__(self, result: dict) -> None:
        self.success = result["success"]
        self.reason = result["reason"]


def check_project_path():
    skip_check_project_path = get_env_variable("SKIP_CHECK_PROJECT_PATH")

    if not skip_check_project_path:
        sci_project_type = get_env_variable("SCI_PROJECT_TYPE")

        graphql_client = GraphqlClient()

        project_path_checker = CheckProjectPath(graphql_client)

        result_check = project_path_checker.check()

        if not result_check.success:
            angular_issue = ""
            custom_issues = CustomIssue(graphql_client)
            custom_issues.rule = "PROJECT_PATH_AND_NAME_ARE_NOT_THE_SAME"
            if sci_project_type in [
                "ANGULAR_APP",
                "ANGULAR_GENERATED",
                "ANGULAR_SENIORX",
                "ANGULAR_APP",
                "ANGULAR_LIB",
            ]:
                angular_issue = " ou o nome do projeto diverge do configurado no arquivo angular.json"
            custom_issues.description = (
                f"O path do projeto e o nome do projeto são diferentes{angular_issue}."
            )

            custom_issues.notification_text = result_check.reason

            today = datetime.today()
            tomorrow = today + timedelta(days=1)

            custom_issues.must_be_fixed_until = tomorrow

            custom_issues.create()
