# coding: utf-8


import logging

from django.conf import settings

from idm.nodes.fetchers import IDSFetcher
from idm.services.canonical import CanonicalService

log = logging.getLogger(__name__)


def add_root_id_recursive(root_id, current):
    for child in current.children:
        child.root_id = root_id
        add_root_id_recursive(root_id, child)


class IDSServiceFetcher(IDSFetcher):
    def fetch(self, node=None):
        lookup = {
            'fields': 'id,parent,state,slug,name,description,tags,membership_inheritance',
            'state__in': 'develop,supported,needinfo,closed',
            'page_size': settings.IDM_ABC_PAGE_SIZE,
        }

        log.info('Fetching services. IDS lookup: %s', lookup)

        service_iterator = self.abc_services_repo.getiter(lookup)
        services = []
        for service_data in service_iterator:
            services.append(CanonicalService(
                hash='',
                external_id=service_data['id'],
                parent_id=service_data['parent']['id'] if service_data['parent'] else None,
                root_id=None,
                state=service_data['state'],
                slug=service_data['slug'].lower() if service_data['slug'] is not None else None,
                name=service_data['name']['ru'],
                name_en=service_data['name']['en'],
                description_wiki=service_data['description']['ru'],
                description_wiki_en=service_data['description']['en'],
                description_html='',
                description_html_en='',
                is_vteam=settings.IDM_ABC_VTEAM_TAG_ID in [tag['id'] for tag in service_data['tags']],
                membership_inheritance=service_data['membership_inheritance'],
            ))
        return self.treeify_data(services)

    def treeify_data(self, items, item_type=None):
        root = super(IDSServiceFetcher, self).treeify_data(items, item_type=item_type)
        for subroot in root.children:
            add_root_id_recursive(subroot.external_id, subroot)
        return root

    def get_root(self, children, item_type=None):
        return CanonicalService(
            hash='',
            external_id=0,
            parent_id=None,
            root_id=None,
            state='supported',
            slug='',
            name='',
            name_en='',
            description_wiki='',
            description_wiki_en='',
            description_html='',
            description_html_en='',
            is_vteam=False,
            children=children,
            membership_inheritance=True,
        )
