# coding: utf-8

import socket

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

from idm.ping.wormholes import check_wormholes

INCLUDE_WORMHOLES = [                                   # [(param_name, (host, port))] - include wormholes explicitly
    ('splunk_log_host', ('jailbot.yandex.net', 3030)),  # админы посылают логи IDM в splunk:3030
]


class Command(BaseCommand):
    help = 'Check if service has all required wormholes available'
    requires_system_checks = False

    def handle(self, *args, **options):
        print('\n')
        print('Checking wormholes availability for', socket.getfqdn(), '...')

        result_q = check_wormholes(settings, include=INCLUDE_WORMHOLES)

        candidates_len = len(result_q)
        failed_len = len([address_name_state1 for address_name_state1 in result_q if address_name_state1[2] in ('timeout', 'not known', 'no route')])

        print('Total:', candidates_len)
        print('Connected:', candidates_len - failed_len)
        print('Failed:', failed_len)
        print('--')

        list(map(lambda host_port_name_state: print('\t\t'.join((host_port_name_state[2], ':'.join((host_port_name_state[0][0], str(host_port_name_state[0][1]))), host_port_name_state[1].upper()))),
            sorted(result_q, key=lambda address_name_state: (address_name_state[2], address_name_state[1], address_name_state[0]))))
