from reportlab.lib import colors

from django.db import models
from django import forms
from django.core import validators
from django.utils.html import escape

COLOR_FIELD_LENGTH = 7

def installColorField():
    import rladminwidget
    rladminwidget.registerJsAdminScript(ColorField, 'js/colorfield.js')


class ColorFormField(forms.TextField):
    "Colour picker field."

    input_type = "text"

    def __init__(self, field_name, is_required=False, validator_list=None):
        validator_list.insert(0, self.validate)
        forms.TextField.__init__(
            self,
            field_name, length=COLOR_FIELD_LENGTH, maxlength=COLOR_FIELD_LENGTH,
            is_required=is_required, validator_list=validator_list)

    def get_internal_type(self):
        return 'ColorField'

    def validate(self, field_data, all_data):
        try:
            isValidRgbColorString(field_data, all_data)
        except validators.ValidationError, e:
            raise validators.CriticalValidationError, e.messages

    def render(self, data):
        if data is None:
            data = ''
        maxlength = ''
        if self.maxlength:
            maxlength = 'maxlength="%s" ' % self.maxlength
        if isinstance(data, unicode):
            data = data.encode(settings.DEFAULT_CHARSET)
        id = self.get_id()+'nonce29493'
        fieldId = id+'field'
        return """\
<!-- flooble.com Color Picker start -->
<a href="javascript:pickColor('%s');" id="%s"
style="border: 1px solid #000000; font-family:Verdana; font-size:10px;
text-decoration: none;">&nbsp;&nbsp;&nbsp;</a>
<input id="%s" size="7" 
onchange="relateColor('%s', this.value);" name="%s" value="%s" />
<script type="text/javascript">relateColor('%s', getObj('%s').value);</script>
<!-- flooble Color Picker end -->
""" % (id, id, fieldId, id, self.field_name, escape(data), id, fieldId)
##         '<input type="%s" id="%s" class="v%s%s" name="%s" size="%s" value="%s" %s/>' % \
##             (self.input_type, self.get_id(), self.__class__.__name__, self.is_required and ' required' or '',
##             self.field_name, self.length, escape(data), maxlength)



class ColorField(models.Field):

    def get_manipulator_field_objs(self):
        return [ColorFormField]


def isValidRgbColorString(field_data, all_data):
    try:
        colors.HexColor(field_data, htmlOnly=True)
    except ValueError:
        raise validators.ValidationError('The submitted color is not recognised.')


installColorField()
