# -*- coding: utf-8 -*-


import logging

from django.db.models import Q

from idm.core.constants.rolenode import ROLENODE_STATE
from idm.core.management.base import IdmBaseCommand
from idm.core.models import RoleNode

log = logging.getLogger(__name__)


class Command(IdmBaseCommand):
    help = 'Пушим в Intrasearch ноды, изменения по которым не были отправлены.'

    # ToDo: поправить после https://st.yandex-team.ru/IDM-7779
    intranet_only = True

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--system', type='system', required=False
        )

    def idm_handle(self, *args, **options):
        filtered_nodes = (
                Q(need_isearch_push_method__isnull=False) &
                Q(state__in=ROLENODE_STATE.TERMINAL) &
                Q(is_key=False)
        )
        system = options.get('system')
        if system:
            filtered_nodes &= Q(system=system)
        log.info('Start pushing nodes to Intrasearch')
        for node in RoleNode.objects.filter(filtered_nodes):
            node.send_intrasearch_push(node.need_isearch_push_method)
        log.info('Nodes have been pushed to Intrasearch')
