from django.contrib import admin

from .models import CouponVote, StoreComment


def approve_selected(modeladmin, request, queryset):
    updated = queryset.update(approved=True)
    modeladmin.message_user(request, "%d comment(s) approved." % updated)


approve_selected.short_description = "Approve selected comments (show on site)"


def hide_selected(modeladmin, request, queryset):
    updated = queryset.update(approved=False)
    modeladmin.message_user(request, "%d comment(s) hidden." % updated)


hide_selected.short_description = "Hide selected comments"


class StoreCommentAdmin(admin.ModelAdmin):
    list_display = ("store_slug", "name", "short_body", "approved", "created_at")
    list_editable = ("approved",)
    list_filter = ("approved", "created_at")
    search_fields = ("store_slug", "name", "email", "body")
    readonly_fields = ("created_at", "ip_hash")
    fields = ("store_slug", "name", "email", "body", "approved", "reply", "created_at", "ip_hash")
    actions = (approve_selected, hide_selected)
    date_hierarchy = "created_at"

    def short_body(self, obj):
        return (obj.body[:90] + "...") if len(obj.body) > 90 else obj.body

    short_body.short_description = "Comment"


class CouponVoteAdmin(admin.ModelAdmin):
    list_display = ("coupon_id", "store_slug", "worked", "updated_at")
    list_filter = ("worked", "updated_at")
    search_fields = ("store_slug", "coupon_id")
    readonly_fields = ("coupon_id", "store_slug", "worked", "voter_hash", "created_at", "updated_at")

    def has_add_permission(self, request, *args):
        # Votes only come from real visitors on the site.
        return False


admin.site.register(StoreComment, StoreCommentAdmin)
admin.site.register(CouponVote, CouponVoteAdmin)
