# coding: utf-8


import logging

from django.utils.translation import ugettext as _

from idm.api.frontend.apifields import ServiceNoRecursionForeignKey
from idm.api.frontend.base import FrontendApiResource
from idm.services.models import Service

log = logging.getLogger(__name__)


class ServiceResource(FrontendApiResource):

    parent = ServiceNoRecursionForeignKey(attribute='parent')
    root = ServiceNoRecursionForeignKey(attribute='root')

    class Meta(FrontendApiResource.Meta):
        abstract = False
        object_class = Service
        queryset = Service.objects.nonroot()
        resource_name = 'services'
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        detail_uri_name = 'slug'
        fields = [
            'parent',
            'root',
            'name',
            'description_wiki',
            'description_html',
            'external_id',
            'external_state',
            'slug',
            'state',
            'is_vteam',
            'created_at',
            'updated_at',
        ]
        limit = 100

    def dehydrate(self, bundle):
        bundle = super(ServiceResource, self).dehydrate(bundle)

        bundle.data['id'] = bundle.data.pop('external_id')
        bundle.data['state'] = bundle.data.pop('external_state')
        bundle.data['name'] = bundle.obj.get_localized_field('name')
        bundle.data['description_wiki'] = bundle.obj.get_localized_field('description_wiki')
        bundle.data['description_html'] = bundle.obj.get_localized_field('description_html')

        return bundle


class ServiceNoRecursionResource(ServiceResource):

    class Meta(ServiceResource.Meta):
        fields = [field for field in ServiceResource.Meta.fields if field not in ('parent', 'root')]
