from datetime import datetime

from common import get_env_variable_required
from common.graphql_client import GraphqlClient


class CustomIssue(object):
    """Entity of a Custom Issue"""

    rule: str
    must_be_fixed_until: datetime
    description: str
    notification_text: str

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

    def create(self):
        """Create a CustomIssue for project"""

        query = """
            mutation ($projectId: Int!, $customIssue: CustomIssueInput!) {
                createCustomCiIssue(
                    customIssueInfo: $customIssue
                    gitlabInfo:{
                        projectId: $projectId
                    }
                ) {
                    success
                    message
                }
            }
        """

        params = {
            "projectId": int(get_env_variable_required("CI_PROJECT_ID")),
            "customIssue": self.convert_to_json(),
        }

        self.client_graphql.call(query, params)

    def convert_from_json(self, payload):
        """Convert a payload to this class"""

        self.rule = payload["rule"]
        self.must_be_fixed_until = payload["mustBeFixedUntil"]

        if self.must_be_fixed_until:
            self.must_be_fixed_until = datetime.strptime(
                self.must_be_fixed_until, "%Y-%m-%dT%H:%M:%S"
            )

        self.description = payload["description"]
        self.notification_text = payload["notificationText"]

        return self

    def convert_to_json(self):
        """Convert this class to a json"""

        return {
            "rule": self.rule,
            "mustBeFixedUntil": self.must_be_fixed_until.strftime("%Y-%m-%dT%H:%M:%S"),
            "description": self.description,
            "notificationText": self.notification_text,
        }
