# Path: dash/categories/fields.py
# class CategoryChoiceField(forms.ModelChoiceField):
#     def label_from_instance(self, obj):
#         return obj.get_label_from_instance()
# 
# Path: dash/orgs/views.py
# class OrgObjPermsMixin(OrgPermsMixin):
#     def get_object_org(self):
#         return self.get_object().org
# 
#     def has_org_perm(self, codename):
#         has_org_perm = super(OrgObjPermsMixin, self).has_org_perm(codename)
# 
#         if has_org_perm:
#             user = self.get_user()
# 
#             if user.is_anonymous:
#                 return True
#             return user.get_org() == self.get_object_org()
# 
#         return False
# 
#     def has_permission(self, request, *args, **kwargs):
#         has_perm = super(OrgObjPermsMixin, self).has_permission(request, *args, **kwargs)
# 
#         if has_perm:
#             user = self.get_user()
# 
#             # user has global permission
#             if user.has_perm(self.permission):
#                 return True
# 
#             return user.get_org() == self.get_object_org()
# 
#         return False
# 
# class OrgPermsMixin(object):
#     """
#     Get the organisation and the user within the inheriting view so that it be
#     come easy to decide whether this user has a certain permission for that
#     particular organization to perform the view's actions
#     """
# 
#     def get_user(self):
#         return self.request.user
# 
#     def derive_org(self):
#         return self.request.org
# 
#     def pre_process(self, request, *args, **kwargs):
#         user = self.get_user()
#         org = self.derive_org()
# 
#         if user.is_superuser:
#             return None
# 
#         if not org:
#             return HttpResponseRedirect(reverse("orgs.org_choose"))
# 
#         return None
# 
#     def has_org_perm(self, permission):
#         (app_label, codename) = permission.split(".")
# 
#         if self.get_user().is_superuser:
#             return True
# 
#         if self.get_user().is_anonymous:
#             return False
# 
#         if self.org:
#             org_group = self.get_user().get_org_group()
#             if org_group:
#                 if org_group.permissions.filter(content_type__app_label=app_label, codename=codename).exists():
#                     return True
# 
#         return False
# 
#     def has_permission(self, request, *args, **kwargs):
#         """
#         Figures out if the current user has permissions for this view.
#         """
#         self.kwargs = kwargs
#         self.args = args
#         self.request = request
#         self.org = self.derive_org()
# 
#         if self.get_user().is_superuser:
#             return True
# 
#         if self.get_user().has_perm(self.permission):
#             return True
# 
#         return self.has_org_perm(self.permission)
# 
# Path: dash/categories/models.py
# class Category(SmartModel):
#     """
#     Every organization can choose to categorize their polls or stories
#     according to their needs.
#     """
# 
#     name = models.CharField(max_length=64, help_text=_("The name of this category"))
# 
#     image = models.ImageField(
#         upload_to=partial(generate_file_path, "categories"),
#         null=True,
#         blank=True,
#         help_text=_("An optional image that can describe this category"),
#     )
# 
#     org = models.ForeignKey(
#         Org,
#         on_delete=models.PROTECT,
#         related_name="categories",
#         help_text=_("The organization this category applies to"),
#     )
# 
#     def get_first_image(self):
#         cat_images = self.images.filter(is_active=True).exclude(image="")
#         if cat_images and cat_images.first().image:
#             return cat_images.first().image
# 
#     def get_label_from_instance(self):
#         label = str(self)
#         if isinstance(label, bytes):
#             label = label.decode("utf-8")
# 
#         if not self.is_active:
#             label = "%s %s" % (label, "(Inactive)")
#         return label
# 
#     def __str__(self):
#         return "%s - %s" % (self.org, self.name)
# 
#     class Meta:
#         ordering = ["name"]
#         unique_together = ("name", "org")
#         verbose_name_plural = _("Categories")
# 
# class CategoryImage(SmartModel):
#     name = models.CharField(max_length=64, help_text=_("The name to describe this image"))
# 
#     category = models.ForeignKey(
#         Category, on_delete=models.PROTECT, related_name="images", help_text=_("The category this image represents")
#     )
# 
#     image = models.ImageField(
#         upload_to=partial(generate_file_path, "categories"), help_text=_("The image file to use")
#     )
# 
#     def __str__(self):
#         return "%s - %s" % (self.category.name, self.name)


from smartmin.views import SmartCreateView, SmartCRUDL, SmartListView, SmartUpdateView
from django import forms
from dash.categories.fields import CategoryChoiceField
from dash.orgs.views import OrgObjPermsMixin, OrgPermsMixin
from .models import Category, CategoryImage





class CategoryImageForm(forms.ModelForm):
    category = CategoryChoiceField(Category.objects.none())

    def __init__(self, *args, **kwargs):
        self.org = kwargs["org"]
        del kwargs["org"]

        super(CategoryImageForm, self).__init__(*args, **kwargs)
        self.fields["category"].queryset = Category.objects.filter(org=self.org).order_by("name")

    class Meta:
        model = CategoryImage
        fields = ("is_active", "name", "category", "image")


class CategoryCRUDL(SmartCRUDL):
    model = Category
    actions = ("create", "update", "list")

    class Update(OrgObjPermsMixin, SmartUpdateView):
        fields = ("is_active", "name")


# Path: dash/categories/fields.py
# class CategoryChoiceField(forms.ModelChoiceField):
#     def label_from_instance(self, obj):
#         return obj.get_label_from_instance()
# 
# Path: dash/orgs/views.py
# class OrgObjPermsMixin(OrgPermsMixin):
#     def get_object_org(self):
#         return self.get_object().org
# 
#     def has_org_perm(self, codename):
#         has_org_perm = super(OrgObjPermsMixin, self).has_org_perm(codename)
# 
#         if has_org_perm:
#             user = self.get_user()
# 
#             if user.is_anonymous:
#                 return True
#             return user.get_org() == self.get_object_org()
# 
#         return False
# 
#     def has_permission(self, request, *args, **kwargs):
#         has_perm = super(OrgObjPermsMixin, self).has_permission(request, *args, **kwargs)
# 
#         if has_perm:
#             user = self.get_user()
# 
#             # user has global permission
#             if user.has_perm(self.permission):
#                 return True
# 
#             return user.get_org() == self.get_object_org()
# 
#         return False
# 
# class OrgPermsMixin(object):
#     """
#     Get the organisation and the user within the inheriting view so that it be
#     come easy to decide whether this user has a certain permission for that
#     particular organization to perform the view's actions
#     """
# 
#     def get_user(self):
#         return self.request.user
# 
#     def derive_org(self):
#         return self.request.org
# 
#     def pre_process(self, request, *args, **kwargs):
#         user = self.get_user()
#         org = self.derive_org()
# 
#         if user.is_superuser:
#             return None
# 
#         if not org:
#             return HttpResponseRedirect(reverse("orgs.org_choose"))
# 
#         return None
# 
#     def has_org_perm(self, permission):
#         (app_label, codename) = permission.split(".")
# 
#         if self.get_user().is_superuser:
#             return True
# 
#         if self.get_user().is_anonymous:
#             return False
# 
#         if self.org:
#             org_group = self.get_user().get_org_group()
#             if org_group:
#                 if org_group.permissions.filter(content_type__app_label=app_label, codename=codename).exists():
#                     return True
# 
#         return False
# 
#     def has_permission(self, request, *args, **kwargs):
#         """
#         Figures out if the current user has permissions for this view.
#         """
#         self.kwargs = kwargs
#         self.args = args
#         self.request = request
#         self.org = self.derive_org()
# 
#         if self.get_user().is_superuser:
#             return True
# 
#         if self.get_user().has_perm(self.permission):
#             return True
# 
#         return self.has_org_perm(self.permission)
# 
# Path: dash/categories/models.py
# class Category(SmartModel):
#     """
#     Every organization can choose to categorize their polls or stories
#     according to their needs.
#     """
# 
#     name = models.CharField(max_length=64, help_text=_("The name of this category"))
# 
#     image = models.ImageField(
#         upload_to=partial(generate_file_path, "categories"),
#         null=True,
#         blank=True,
#         help_text=_("An optional image that can describe this category"),
#     )
# 
#     org = models.ForeignKey(
#         Org,
#         on_delete=models.PROTECT,
#         related_name="categories",
#         help_text=_("The organization this category applies to"),
#     )
# 
#     def get_first_image(self):
#         cat_images = self.images.filter(is_active=True).exclude(image="")
#         if cat_images and cat_images.first().image:
#             return cat_images.first().image
# 
#     def get_label_from_instance(self):
#         label = str(self)
#         if isinstance(label, bytes):
#             label = label.decode("utf-8")
# 
#         if not self.is_active:
#             label = "%s %s" % (label, "(Inactive)")
#         return label
# 
#     def __str__(self):
#         return "%s - %s" % (self.org, self.name)
# 
#     class Meta:
#         ordering = ["name"]
#         unique_together = ("name", "org")
#         verbose_name_plural = _("Categories")
# 
# class CategoryImage(SmartModel):
#     name = models.CharField(max_length=64, help_text=_("The name to describe this image"))
# 
#     category = models.ForeignKey(
#         Category, on_delete=models.PROTECT, related_name="images", help_text=_("The category this image represents")
#     )
# 
#     image = models.ImageField(
#         upload_to=partial(generate_file_path, "categories"), help_text=_("The image file to use")
#     )
# 
#     def __str__(self):
#         return "%s - %s" % (self.category.name, self.name)


# Path: dash/categories/views.py
from smartmin.views import SmartCreateView, SmartCRUDL, SmartListView, SmartUpdateView
from django import forms
from dash.categories.fields import CategoryChoiceField
from dash.orgs.views import OrgObjPermsMixin, OrgPermsMixin
from .models import Category, CategoryImage






class CategoryImageForm(forms.ModelForm):
    category = CategoryChoiceField(Category.objects.none())

    def __init__(self, *args, **kwargs):
        self.org = kwargs["org"]
        del kwargs["org"]

        super(CategoryImageForm, self).__init__(*args, **kwargs)
        self.fields["category"].queryset = Category.objects.filter(org=self.org).order_by("name")

    class Meta:
        model = CategoryImage
        fields = ("is_active", "name", "category", "image")


class CategoryCRUDL(SmartCRUDL):
    model = Category
    actions = ("create", "update", "list")

    class Update(OrgObjPermsMixin, SmartUpdateView):
        fields = ("is_active", "name")


    class List(OrgPermsMixin, SmartListView):