import tinymce, tinymce.widgets, tinymce.models

from django.conf import settings
from django.contrib import admin
from django.forms import widgets

from rldjango.apps.crm.models import Lead, CRMTag, Communication, Language, Role, EmailJob


class TagAdmin(admin.ModelAdmin):
    list_display = ('id', 'description')
    search_fields = ('id', 'description')

admin.site.register(CRMTag, TagAdmin)

class LeadAdmin(admin.ModelAdmin):
    help_text = 'Help me...'
    list_display = ('email', 'first_name', 'last_name', 'language', 'country', 'active', 'created', 'updated', 'email_response', 'email_response_communication')
    list_filter = ('email_response', 'role', 'language', 'tags', 'updated')
    ordering = ('-created', )
    search_fields = ('email', 'last_name', 'company', 'tags__id')
    filter_horizontal = ['tags']
    save_on_top = True
    actions = ['bulk_unsubscribe', 'bulk_set_tag']
    fieldsets = (
        (None, {
            'fields': ('email',
                       'first_name', 'middle_name','last_name',
                       'department', 'job_title', 'company',
                       'role', 'country', 'language',
                       'industry','purpose',
                       )
        }),
        ('Tags', {
            'classes': ('collapse',),
            'fields': ('tags',)
        }),
        ('Additional contact info', {
            'classes': ('collapse',),
            'fields': (
                'business_street', 'business_city', 'business_country',
                'other_street', 'other_city', 'other_country',
                'business_fax', 'business_phone', 'mobile_phone', 'other_phone',
                       )
        }),
        ('Tracking', {
            'classes': ('collapse',),
            'fields': (
                'has_bought','last_purchased','active'
                       )
        }),
    )

    def bulk_unsubscribe(self, request, queryset):
        count = 0
        for lead in queryset:
            lead.unsubscribe('unsubscribed by hand')
            count += 1
        self.message_user(request, "%d leads unsubscribed." % count)

    bulk_unsubscribe.short_description = "Unsubscribe leads - no further emails will be sent"

    def bulk_set_tag(self, request, queryset):
        "Redirect to a page allowing a tag to be set"
        selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
        from django.http import HttpResponseRedirect
        return HttpResponseRedirect("/admin/crm/apply_tag/?ids=%s" % (",".join(selected)))

    bulk_set_tag.short_description = "Apply tags to selected leads"

    def save_model(self, request, obj, form, change):
        if not change:
            obj.created_by = request.user
        obj.updated_by = request.user
        obj.save()

admin.site.register(Lead, LeadAdmin)


class CommunicationAdmin(admin.ModelAdmin):
    list_display = ('subject', 'created', 'get_contents_preview', 'preview', 'send')
    search_fields = ('subject', 'message_html', 'message_plain')
    ordering = ('-created',)
    #actions = ['bulk_send_email']

    formfield_overrides = {
            tinymce.models.HTMLField: {'widget': tinymce.widgets.TinyMCE(attrs={'cols':90,
                    'rows': 15,},
                    mce_attrs={
                        'theme': 'modern',
                        'cleanup_on_startup': True,
                        'custom_undo_redo_levels': 10,
                        #'theme_advanced_toolbar_location' : "bottom",
                        #'theme_advanced_blockformats' : "p,h1,h2,h3,h4,h5,h6",
                        #'theme_advanced_statusbar_location' : "none",
                        'plugins' : 'advlist autolink link lists charmap preview code',
                        'toolbar': 'formatselect bold italic alignleft aligncenter alignright | undo redo | link unlink | bulllist numlist indent outdent code',
                        #'theme_advanced_buttons2': '',
                        #'theme_advanced_buttons3': '',
                        'content_css': "/static/cms/css/tiny.css",
                        'extended_valid_elements': "-pre[class|name]",
                        'convert_urls': False,
                        #'theme_advanced_source_editor_wrap' : False,
                        }
                )},
            }

    #def get_form(self, request, obj=None, **kwargs):
    #    _choices = (
    #            (settings.DEFAULT_FROM_EMAIL, 'ReportLab'),
    #            (request.user.email, request.user.get_full_name()),
    #        )
    #    form = super(CommunicationAdmin, self).get_form(request, obj, **kwargs)
    #    sender_field = form.base_fields['sender']
    #    sender_field.widget=widgets.RadioSelect(choices=_choices)
    #    return form

    def bulk_send_email(self, request, queryset):
        "Redirect to the email sending page"
        selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
        from django.http import HttpResponseRedirect
        return HttpResponseRedirect("/admin/crm/send_emails/?id=%s" % (",".join(selected)))

    def send(self, obj):
        "Returns fancy HTML button or whatever"
        return '<a href="/admin/crm/send_emails/?id=%s">Send</a>' % obj.id
    send.allow_tags = True

    def preview(self, obj):
        "Returns fancy HTML button or whatever"
        return '<a href="#" onclick="javascript:window.open(\'/admin/crm/preview_communication/%s/\',\'communication_preview\',\'menubar=no,width=600,height=600,toolbar=no,scrollbars=yes\');">Preview</a>' % obj.id
    preview.allow_tags = True

    bulk_send_email.short_description = "Send emails for selected communications"

admin.site.register(Communication, CommunicationAdmin)


class EmailJobAdmin(admin.ModelAdmin):
    list_display = ('id', 'created', 'tag', 'communication', 'ignore_previously_emailed', 'ignore_previously_emailed_with_same_subject', 'queued')
    search_fields = ('id', 'tag')
    def get_readonly_fields(self,request,obj=None):
        if not obj:
            return ('queued',)
        else:
            return ()
admin.site.register(EmailJob, EmailJobAdmin)


class LanguageAdmin(admin.ModelAdmin):
    list_display = ('id','name')

admin.site.register(Language, LanguageAdmin)

class RoleAdmin(admin.ModelAdmin):
    list_display = ('id','name')

admin.site.register(Role, RoleAdmin)
