# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.http import Http404
from django.utils.safestring import mark_safe
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from horizon import messages
from horizon import tables
from horizon_bsn.api import neutron
from openstack_dashboard.api import heat

import logging

LOG = logging.getLogger(__name__)


class RemoveTemplateAction(tables.LinkAction):
    name = "remove"
    url = "horizon:project:connections:network_template:remove"
    classes = ("ajax-modal", "btn-danger")
    verbose_name = _("Remove Network Template Instance")

    def allowed(self, request, datum):
        try:
            assign = neutron\
                .networktemplateassignment_get(request,
                                               request.user.tenant_id)
            if assign:
                return True
        except Exception as e:
            LOG.debug(e)
            return False


class ApplyTemplateAction(tables.LinkAction):
    name = "apply"
    verbose_name = _("Apply Network Template")
    url = "horizon:project:connections:network_template:select"
    classes = ("ajax-modal", "btn-create")

    def allowed(self, request, datum):
        try:
            assign = neutron\
                .networktemplateassignment_get(request,
                                               request.user.tenant_id)
            if assign:
                return False
        except Exception:
            return True


class StacksUpdateRow(tables.Row):
    ajax = True

    def can_be_selected(self, datum):
        return datum.stack_status != 'DELETE_COMPLETE'

    def get_data(self, request, stack_id):
        assignment = None
        try:
            assignments = neutron.networktemplateassignment_list(
                request, **{'stack_id': stack_id})
            if not assignments:
                raise Exception('Network template associationg not found.')
            assignment = assignments[0]

            template = neutron.networktemplate_get(request,
                                                   assignment.template_id)

            stack = heat.stack_get(request, stack_id)
            resources = heat.resources_list(request, stack.stack_name)
            if stack.stack_status == 'DELETE_COMPLETE':
                # returning 404 to the ajax call removes the
                # row from the table on the ui
                raise Http404
            rowdata = {
                'template_id': assignment.template_id,
                'template_name': template.name,
                'stack_id': stack_id,
                'heat_stack_name': stack.stack_name,
                'description': stack.description,
                'status': stack.status,
                'stack_status': stack.stack_status,
                'stack_status_reason': stack.stack_status_reason,
                'resources': mark_safe('<br>'.join([
                    ('%s (%s)' % (r.resource_name,
                                  r.resource_type)).replace(' ', '&nbsp;')
                    for r in resources]))
            }
            return rowdata
        except Http404:
            try:
                # remove corresponding network template
                if assignment:
                    neutron.networktemplateassignment_delete(
                        request, assignment.id)
                msg = _('Removed template association for stack_id %s') % \
                    stack_id
                LOG.debug(msg)
                messages.success(request, msg)
            except Exception as e:
                msg = _('Network template association removal failed '
                        'due to %s') % e
                LOG.error(msg)
                messages.error(request, msg)
            raise
        except Exception as e:
            raise


class NetworkTemplateTable(tables.DataTable):
    STATUS_CHOICES = (
        ("Complete", True),
        ("Failed", False),
    )