from __future__ import absolute_import

from django.conf import settings
from django.contrib import admin, messages
from django.contrib.auth.forms import (
    UserCreationForm, UserChangeForm, AdminPasswordChangeForm
)
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.http import Http404, HttpResponseRedirect
from django.utils.html import escape
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from django.utils.translation import ugettext, ugettext_lazy as _
from pprint import saferepr
from sentry.models import (
    ApiKey, AuthIdentity, AuthProvider, AuditLogEntry, Broadcast, HelpPage,
    Option, Organization, OrganizationMember, OrganizationMemberTeam, Project,
    Team, User
)

csrf_protect_m = method_decorator(csrf_protect)
sensitive_post_parameters_m = method_decorator(sensitive_post_parameters())


class BroadcastAdmin(admin.ModelAdmin):
    list_display = ('title', 'message', 'is_active', 'date_added')
    list_filter = ('is_active',)
    search_fields = ('title', 'message', 'link')
    readonly_fields = ('upstream_id', 'date_added')

admin.site.register(Broadcast, BroadcastAdmin)


class OptionAdmin(admin.ModelAdmin):
    list_display = ('key', 'last_updated')
    fields = ('key', 'value_repr', 'last_updated')
    readonly_fields = ('key', 'value_repr', 'last_updated')
    search_fields = ('key',)

    def value_repr(self, instance):
        return '<pre style="display:inline-block;white-space:pre-wrap;">{}</pre>'.format(escape(saferepr(instance.value)))

    value_repr.short_description = "Value"
    value_repr.allow_tags = True


admin.site.register(Option, OptionAdmin)


class ProjectAdmin(admin.ModelAdmin):
    list_display = ('name', 'slug', 'organization', 'status', 'date_added')
    list_filter = ('status', 'public')
    search_fields = ('name', 'organization__slug', 'organization__name', 'team__slug',
                     'team__name', 'slug')
    raw_id_fields = ('team', 'organization')
    readonly_fields = ('first_event', 'date_added')

admin.site.register(Project, ProjectAdmin)


class OrganizationApiKeyInline(admin.TabularInline):
    model = ApiKey
    extra = 1
    fields = ('label', 'key', 'status', 'allowed_origins', 'date_added')
    raw_id_fields = ('organization',)


class OrganizationProjectInline(admin.TabularInline):
    model = Project
    extra = 1
    fields = ('name', 'slug', 'status', 'date_added')
    raw_id_fields = ('organization', 'team')


class OrganizationTeamInline(admin.TabularInline):
    model = Team
    extra = 1
    fields = ('name', 'slug', 'status', 'date_added')
    raw_id_fields = ('organization',)


class OrganizationMemberInline(admin.TabularInline):
    model = OrganizationMember