from logging import getLogger
from datetime import datetime, timedelta

from django.conf import settings

from intranet.search.core.management.commands.reindex import Command as BaseCommand
from intranet.search.core.storages import OrganizationStorage
from intranet.search.core.tvm import tvm2_client
from intranet.search.core.utils import convert_timeout, http

logger = getLogger(__name__)


class Command(BaseCommand):
    help = 'Make and deploy new wiki index only for changed organizations'

    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument('--reindex-delta', action='store', default='1h',
                            help='reindex organizations changed in last <delta> time')

    def handle(self, **options):
        logger.info('Start reindex wiki')
        ts = options['ts']
        if not ts:
            ts = datetime.utcnow() - timedelta(seconds=convert_timeout(options['reindex_delta']))
            ts = ts.strftime('%s')

        options['organizations'] = self.get_changed_organizations(ts)
        options['search'] = 'wiki'
        logger.info('Organizations with updated wiki since %s: %s', ts, options['organizations'])
        super().handle(**options)

    def get_changed_organizations(self, ts):
        """ Возвращает список измененных начиная с ts организаций
        """
        org_storage = OrganizationStorage()
        # апи измененных организаций нужно запрашивать от имени любой организации
        org = org_storage.get_by_service('wiki', limit=1)[0]

        endpoint = settings.ISEARCH['api']['wiki']['wiki_changed_orgs']
        query = {'since': ts}

        headers = endpoint.headers()
        headers[settings.TVM2_SERVICE_HEADER] = tvm2_client.get_service_ticket('wiki')
        headers['X-Org-Id'] = str(org['directory_id'])
        session = http.create_session(
            verify=settings.ISEARCH_CA_BUNDLE,
            headers=headers,
        )
        response = http.call_with_retry(session.get, endpoint.url(query=query))
        organizations = response.json()['data']
        return organizations
