import redminelib
from django.conf import settings
from django.core.management.base import BaseCommand
from redminelib import Redmine

from scrutiny.projects.models import Module
from scrutiny.projects.utils import get_issue_deployment_status


class Command(BaseCommand):
    def handle(self, verbosity, *args, **options):
        self.redmine_server = Redmine(
            settings.REDMINE_URL, key=settings.REDMINE_API_KEY, impersonate=settings.REDMINE_IMPERSONATE
        )
        RESOLVED_ID = None
        DEPLOYED_ID = None

        for issue_status in self.redmine_server.issue_status.all():
            if issue_status.name == 'Résolu (à déployer)':
                RESOLVED_ID = issue_status.id
            elif issue_status.name == 'Solution déployée':
                DEPLOYED_ID = issue_status.id

        for module in Module.objects.all():
            if not module.repository_url:
                continue

            try:
                issues = list(
                    self.redmine_server.issue.filter(
                        project_id=module.redmine_project, status_id=RESOLVED_ID, include=['relations']
                    )
                )
            except redminelib.exceptions.ResourceNotFoundError:
                if verbosity > 1:
                    print('unknown redmine module:', module.name)
                continue
            for issue in issues:
                deployment_status = get_issue_deployment_status(issue.id)
                if not deployment_status.get('platforms'):
                    if verbosity > 1:
                        print(
                            '  unknown status for https://dev.entrouvert.org/issues/%s (%s)'
                            % (issue.id, module.redmine_project)
                        )
                    continue
                platforms_ok = [
                    x.rsplit(' / ', 1)[0]
                    for x in deployment_status['platforms'].keys()
                    if deployment_status['platforms'][x]['status'] == 'ok'
                ]
                if settings.REDMINE_REFERENCE_PLATFORM in platforms_ok:
                    if verbosity > 0:
                        print(
                            '%s - https://dev.entrouvert.org/issues/%s' % (module.redmine_project, issue.id)
                        )
                    issue.status_id = DEPLOYED_ID
                    issue.save()
                    for relation in issue.relations:
                        related_issue_id = (
                            relation.issue_id if relation.issue_id != issue.id else relation.issue_to_id
                        )
                        self.update_related_issue(related_issue_id, RESOLVED_ID)

    def update_related_issue(self, issue_id, target_status_id):
        issue = self.redmine_server.issue.get(issue_id)

        custom_fields = list(issue.custom_fields.values())
        for field in custom_fields:
            if field['name'] == 'En attente d’un développement' and field['value'] == '1':
                waiting_for_dev_field = field
                break
        else:
            return

        issue.status_id = target_status_id
        issue.assigned_to_id = issue.author.id
        issue.notes = (
            'Le développement attendu est disponible sur votre instance de recette. '
            'N’hésitez pas à fermer le ticket après avoir vérifié son bon fonctionnement. '
            'Merci !'
        )

        waiting_for_dev_field['value'] = '0'
        issue.custom_fields = custom_fields
        issue.save()
