from django.core.urlresolvers import reverse

from freenasUI.api.utils import (
    DojoModelResource, DjangoAuthentication, DojoPaginator
)
from freenasUI.middleware.notifier import notifier
from freenasUI.storage.models import Volume
from .models import Failover

class CARPResourceMixin(object):

    def dehydrate(self, bundle):
        bundle = super(CARPResourceMixin, self).dehydrate(bundle)
        if self.is_webclient(bundle.request):
            bundle.data['carp_interface'] = bundle.obj.carp_interface.int_interface
        else:
            bundle.data['carp_interface'] = bundle.obj.carp_interface.id
        return bundle


class FailoverResource(DojoModelResource):

    class Meta:
        queryset = Failover.objects.all()
        resource_name = 'failover/failover'
        paginator_class = DojoPaginator
        authentication = DjangoAuthentication()
        include_resource_uri = False
        allowed_methods = ['get']

    def dehydrate(self, bundle):
        bundle = super(FailoverResource, self).dehydrate(bundle)
        #bundle.data['volume'] = unicode(bundle.obj.volume)
        #FIXME: This makes no sense at all, volume field should be removed
        bundle.data['volume'] = [
            unicode(v.vol_name)
            for v in Volume.objects.filter(vol_fstype='ZFS')
        ]
        bundle.data['carp'] = unicode(bundle.obj.carp)
        bundle.data['_syncfrom_url'] = reverse(
            'failover_sync_from_peer',
            kwargs={'oid': bundle.obj.id},
        )
        if notifier().failover_status() == 'MASTER':
            bundle.data['_syncto_url'] = reverse(
                'failover_sync_to_peer',
                kwargs={'oid': bundle.obj.id},
            )
        return bundle
