from django.conf import settings

import logging

from staff.lib.requests import get_ids_repository

from .messages import MessageThread, Message

logger = logging.getLogger(__name__)


class StartrekIssueMessageThread(MessageThread):
    transport_id = 'startrek_issue'

    def increment(self, msg_id):
        pass

    def get_new_id(self):
        return None


class StartrekCommentMessageThread(MessageThread):
    transport_id = 'startrek_comment'

    def increment(self, msg_id):
        pass

    def get_new_id(self):
        return None


class StartrekMessage(Message):

    def __init__(self, *args, **kwargs):
        self.ids_user_agent = kwargs.pop('ids_user_agent', 'django_intranet_notifications')
        super(StartrekMessage, self).__init__(*args, **kwargs)

    def get_issues_repository(self):
        return get_ids_repository(
            service='startrek2',
            resource_type='issues',
            oauth_token=settings.ROBOT_STAFF_OAUTH_TOKEN,
            user_agent=self.ids_user_agent,
        )


class StartrekIssueMessage(StartrekMessage):

    def __init__(self, *args, **kwargs):
        super(StartrekIssueMessage, self).__init__(*args, **kwargs)

    def get_components_repository(self):
        return get_ids_repository(
            service='startrek2',
            resource_type='components',
            oauth_token=settings.ROBOT_STAFF_OAUTH_TOKEN,
            user_agent=self.ids_user_agent,
        )

    def prepare_fields(self, author, params):
        # TODO Выпилить этот код, когда избавимся от старых id
        result = []
        components_repo = None

        for component in params.get('components', []):
            try:
                result.append(int(component))
            except ValueError:
                if components_repo is None:
                    components_repo = self.get_components_repository()
                result.append(components_repo.get(component).id)

        params['components'] = result

    def create_issue(self, author, **params):
        queue = params.pop('queue')
        issues = self.get_issues_repository()
        self.prepare_fields(author, params)
        description, summary = self.render()

        logger.info(
            'Create startrek issue in queue "%s" with summary "%s"',
            queue,
            summary,
        )

        issue = issues.create(
            createdBy=author.login, queue=queue, summary=summary, description=description, **params
        )

        logger.info('New issue id: "%s", key: "%s"', issue.id, issue.key)

        return issue

    def send(self, **params):
        issue = self.create_issue(**params)
        self.set_id(issue['key'])
        return issue


class StartrekCommentMessage(StartrekMessage):

    def __init__(self, *args, **kwargs):
        super(StartrekCommentMessage, self).__init__(*args, **kwargs)

    def create_comment(self, author, issue_key):
        issues = self.get_issues_repository()

        issue = issues.get(issue_key)[0]

        text = self.render()[0]

        logger.info(
            'Create startrek comment in issue: "%s", with text: "%s"',
            issue.key,
            text,
        )

        text = '@{login}:\n<[{text}]>'.format(login=author.login, text=text)
        comment = issue.comments.create(text=text)

        logger.info("New comment id: %s", comment.id)

        return comment

    def send(self, **params):
        comment = self.create_comment(**params)
        self.set_id(comment.id)
