import openstack_api
from common.models import humanize_exception
from common.operations import Operation, register_operation
from django.core.exceptions import PermissionDenied
from django.utils.translation import ugettext_noop
from openstack_api.neutron import Network
from django.utils.translation import ugettext_lazy as _

class NetworkOperation(Operation):
    host_cls = Network
    os_policy_actions = None

    def __init__(self, instance):
        super(NetworkOperation, self).__init__(subject=instance)
        self.instance = instance

    def check_precond(self):
        pass

    def check_auth(self, user, request):
        if self.os_policy_actions:
            from django.utils.module_loading import import_string
            check = import_string("openstack_auth.policy.check")

            has_rights = check(self.os_policy_actions, request,
                                      {'project_id': self.instance.tenant_id})

            if not has_rights:
                raise humanize_exception(ugettext_noop(
                    "operation not permitted"),
                    PermissionDenied())

        super(NetworkOperation, self).check_auth(user=user)

    def is_preferred(self):
        """If this is the recommended op in the current state of the instance.
        """
        return False

@register_operation
class DeleteNetworkOperation(NetworkOperation):
    id = 'delete_network'
    name = _("delete network")
    description = _("Delete network and all associated resources.")
    os_policy_actions = (
        ("network", "network:delete"),
    )

    #TODO: remove attached interfaces, delete ports and assigned floating ips

    def _operation(self, request):
        ports = openstack_api.neutron.port_list(request, network=self.instance.id)
        network_ports = [p for p in ports if p.network_id == self.instance.id]

        for p in network_ports:
            if p.device_owner == "network:router_interface":
                openstack_api.neutron.router_remove_interface(request, p.device_id, port_id=p.id)
            if p.device_owner == "compute:nova":
                openstack_api.neutron.port_delete(request, p.id)
            # openstack_api.neutron.port_delete(request, p.id)
        openstack_api.neutron.network_delete(request, self.instance.id)
