import re
from datetime import datetime, timedelta

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

from .custom_issue import CustomIssue


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

    def check(self):
        """Check if project is using the latest version of platform"""

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

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

        result = self.client_graphql.call(query, params)
        output = CheckPlatformVersionResponse(result["checkPlatformVersion"])

        return output


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


def check_platform_version():
    skip_check_platform_version = get_env_variable("SKIP_PLATFORM_VERSION_VALIDATION")
    sci_project_type = get_env_variable("SCI_PROJECT_TYPE")

    if not skip_check_platform_version and sci_project_type in [
        "MAVEN_SDL",
    ]:

        graphql_client = GraphqlClient()

        check_platform_version = CheckPlatformVersion(graphql_client)

        result = check_platform_version.check()

        if not result.success:
            custom_issues = CustomIssue(graphql_client)
            custom_issues.rule = "OUTDATED_PLATFORM_VERSION"
            custom_issues.description = result.reason
            custom_issues.notification_text = result.reason

            today = datetime.today()
            in_15_days = today + timedelta(days=15)

            custom_issues.must_be_fixed_until = in_15_days

            custom_issues.create()
