from typing import Dict, List

from ids.services.startrek2.repositories.base import StBaseRepository


service_queues: Dict[str, str] = {
    'Стафф': 'staff',
}

default_queue_tags: Dict[str, List[str]] = {
    'staff': ['duty'],
}


class CreateServiceTicketException(Exception):
    pass


def create_service_ticket(
    repository: StBaseRepository,
    issue,
    comment,
) -> str:
    created_issue = repository.get(lookup={'filter': f'unique:{comment.longId}'})
    if created_issue:
        return created_issue[0].key

    hints = comment.text.strip().split('\n', 2)
    command_params = hints[0].strip().split(' ')
    command = command_params[0].strip()
    command_params = command_params[1:]
    command_params = [p for p in command_params if p]
    queue = command_params[0] if len(command_params) > 0 else None
    desired_tags = (command_params[1] if len(command_params) > 1 else '').split(',')
    desired_tags = [t for t in desired_tags if t]
    title = (hints[1] if len(hints) > 1 else issue.summary) or ''
    description = (hints[2] if len(hints) > 2 else issue.description) or ''

    if not queue:
        for abc_service in issue.abcService:
            queue = service_queues.get(abc_service.name)
            if queue:
                break

    if not queue:
        raise CreateServiceTicketException('In which queue new ticket to be created?')

    tags = desired_tags or default_queue_tags.get(queue.lower())

    issue_params = {
        'author': comment.createdBy.login,
        'queue': queue,
        'summary': title.strip(),
        'description': 'Created from ' + issue.key + '\n' + description.strip(),
        'unique': comment.longId,
    }

    if command == '/child':
        issue_params['links'] = [{'relationship': 'IS_SUBTASK_FOR', 'issue': issue.key}]

    if tags:
        issue_params['tags'] = tags

    return repository.create(**issue_params).key
