# coding=UTF-8
from django.core.urlresolvers import reverse
from django.utils.encoding import force_unicode
from django.utils.encoding import smart_str
from django.utils.safestring import mark_safe
from django.db.models.sql.query import LOOKUP_SEP
from django.db.models.fields.related import ForeignObjectRel as RelatedObject
from django.utils.translation import ugettext as _
from django.db import models

from xadmin.sites import site
from xadmin.views import BaseAdminPlugin, ListAdminView, CreateAdminView, UpdateAdminView, DeleteAdminView

RELATE_PREFIX = '_rel_'


class RelateMenuPlugin(BaseAdminPlugin):

    related_list = []
    use_related_menu = True

    def get_related_list(self):
        if hasattr(self, '_related_acts'):
            return self._related_acts

        _related_acts = []
        for r in self.opts.get_all_related_objects() + self.opts.get_all_related_many_to_many_objects():
            if self.related_list and (r.get_accessor_name() not in self.related_list):
                continue
            related_model = r.related_model
            if related_model not in self.admin_site._registry.keys():
                continue
            has_view_perm = self.has_model_perm(related_model, 'view')
            has_add_perm = self.has_model_perm(related_model, 'add')
            if not (has_view_perm or has_add_perm):
                continue

            _related_acts.append((r, has_view_perm, has_add_perm))

        self._related_acts = _related_acts
        return self._related_acts

    def related_link(self, instance):
        links = []
        for r, view_perm, add_perm in self.get_related_list():
            m = r.related_model._meta
            label = m.app_label
            model_name = m.model_name
            # label = r.opts.app_label
            # model_name = r.opts.model_name
            f = r.field
            rel_name = f.rel.get_related_field().name

            verbose_name = force_unicode(m.verbose_name)
            lookup_name = '%s__%s__exact' % (f.name, rel_name)

            link = ''.join(('<li class="with_menu_btn">',

                            '<a href="%s?%s=%s" title="%s"><i class="icon fa fa-th-list"></i> %s</a>' %
                          (
                            reverse('%s:%s_%s_changelist' % (
                                    self.admin_site.app_name, label, model_name)),
                            RELATE_PREFIX + lookup_name, str(instance.pk), verbose_name, verbose_name) if view_perm else
                            '<a><span class="text-muted"><i class="icon fa fa-blank"></i> %s</span></a>' % verbose_name,

                            '<a class="add_link dropdown-menu-btn" href="%s?%s=%s"><i class="icon fa fa-plus pull-right"></i></a>' %
                          (