import re

from django import forms
from django.forms.util import ErrorList
from django.forms.widgets import HiddenInput, SelectMultiple

from crits.core import form_consts
from crits.core.handlers import get_source_names, get_item_names, ui_themes
from crits.core.user_role import UserRole
from crits.core.user_tools import get_user_organization
from crits.config.config import CRITsConfig
from crits import settings

def add_bucketlist_to_form(input_form):
    """
    Add a bucket_list field to a form.

    :param input_form: The form to add to.
    :type input_form: :class:`django.forms.Form`
    :returns: :class:`django.forms.Form`
    """

    input_form.fields[form_consts.Common.BUCKET_LIST_VARIABLE_NAME] = \
            forms.CharField(widget=forms.TextInput,
                            required=False,
                            label=form_consts.Common.BUCKET_LIST,
                            help_text="Use comma separated values.")

def add_ticket_to_form(input_form):
    """
    Add a tickets field to a form.

    :param input_form: The form to add to.
    :type input_form: :class:`django.forms.Form`
    :returns: :class:`django.forms.Form`
    """

    input_form.fields[form_consts.Common.TICKET_VARIABLE_NAME] = \
            forms.CharField(widget=forms.TextInput,
                            required=False,
                            label=form_consts.Common.TICKET,
                            help_text="Use comma separated values.")

class AddSourceForm(forms.Form):
    """
    Django form for adding a new source to CRITs.
    """

    error_css_class = 'error'
    required_css_class = 'required'
    source = forms.CharField(widget=forms.TextInput, required=True)

class AddReleasabilityForm(forms.Form):
    """
    Django form for adding a new releasability instance to a top-level object.
    """

    error_css_class = 'error'
    required_css_class = 'required'
    source = forms.ChoiceField(required=True, widget=forms.Select)

    def __init__(self, username, *args, **kwargs):
        super(AddReleasabilityForm, self).__init__(*args, **kwargs)
        self.fields['source'].choices = [(c.name,
                                          c.name) for c in get_source_names(True,
                                                                               True,
                                                                               username)]

class NavMenuForm(forms.Form):
    """
    Django form for the user preferences navigation menu.
    """

    error_css_class = 'error'
    required_css_class = 'required'

    DEFAULT_TExT_COLOR = "#FFF"
    DEFAULT_BACKGROUND_COLOR = '#464646'
    DEFAULT_HOVER_TEXT_COLOR = '#39F'
    DEFAULT_HOVER_BACKGROUND_COLOR = '#6F6F6F'

    nav_menu = forms.ChoiceField(widget=forms.RadioSelect(), initial="default",
                                 help_text="Colors currently only work with topmenu. \
                                 Examples of valid color codes: #39F or #9AAED8.")
    text_color = forms.CharField(label="Text Color", initial=DEFAULT_TExT_COLOR,
                                 help_text="Default: " + DEFAULT_TExT_COLOR)
    background_color = forms.CharField(label="Background Color", initial=DEFAULT_BACKGROUND_COLOR,
                                       help_text="Default: " + DEFAULT_BACKGROUND_COLOR)
    hover_text_color = forms.CharField(label="Hover Text Color", initial=DEFAULT_HOVER_TEXT_COLOR,
                                       help_text="Default: " + DEFAULT_HOVER_TEXT_COLOR)
    hover_background_color = forms.CharField(label="Hover Background Color", initial=DEFAULT_HOVER_BACKGROUND_COLOR,
                                             help_text="Default: " + DEFAULT_HOVER_BACKGROUND_COLOR)

    def __init__(self, request, *args, **kwargs):
        super(NavMenuForm, self).__init__(*args, **kwargs)

        prefs = request.user.prefs
        for k in prefs.nav:
            if k in self.fields:
                self.fields[k].initial = prefs.nav[k]

        self.fields['nav_menu'].choices = [('default','default'),
                                        ('topmenu','topmenu')]

    def clean(self):
        cleaned_data = super(NavMenuForm, self).clean()

        def check_hex_color(self, color_code, field_name):
            if not re.match('^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$', color_code):
                self._errors.setdefault(field_name, ErrorList())
                self._errors[field_name].append("This is not a valid color code. Valid examples: #39F or #9AAED8")

        check_hex_color(self, cleaned_data.get('text_color'), 'text_color')
        check_hex_color(self, cleaned_data.get('background_color'), 'background_color')
        check_hex_color(self, cleaned_data.get('hover_text_color'), 'hover_text_color')
        check_hex_color(self, cleaned_data.get('hover_background_color'), 'hover_background_color')

        return cleaned_data

class PrefUIForm(forms.Form):
    """
    Django form for the user preferences interface.
    """

    error_css_class = 'error'
    required_css_class = 'required'
    theme = forms.ChoiceField(required=True, widget=forms.Select,
                              initial="default")

    # layeredthemes = forms.MultipleChoiceField(required=True,
    #                                           label="Layer Themes",
    #                                           help_text="Pick Themes to use",
    #                                           widget=forms.SelectMultiple)
    table_page_size = forms.IntegerField(required=True, min_value = 2, max_value = 10000,
                                         initial=25)

    def __init__(self, request, *args, **kwargs):
        super(PrefUIForm, self).__init__(*args, **kwargs)

        prefs = request.user.prefs
        for k in prefs.ui:
            if k in self.fields:
                self.fields[k].initial = prefs.ui[k]

#        self.fields['layeredthemes'].choices = self.fields['theme'].choices

        self.fields['theme'].choices = [(t,
                                          t) for t in ui_themes()]

class ToastNotificationConfigForm(forms.Form):
    """
    Django form for the user toast notifications.
    """

    error_css_class = 'error'
    required_css_class = 'required'
    enabled = forms.BooleanField(initial=True, required=False)
    max_visible_notifications = forms.IntegerField(min_value = 1,
                                                   max_value = 10,
                                                   initial=5,
                                                   required=False,
                                                   label="Max Visible Notifications")
    acknowledgement_type = forms.ChoiceField(widget=forms.Select,
                                             initial="sticky",
                                             required=False,
                                             label="Acknowledgement Type")
    notification_anchor_location = forms.ChoiceField(widget=forms.Select,
                                                     initial="bottom_right",
                                                     required=False,
                                                     label="Anchor Location")
    newer_notifications_location = forms.ChoiceField(widget=forms.Select,
                                                     initial="top",
                                                     required=False,
                                                     label="Newer Notifications Located")
    initial_notifications_display = forms.ChoiceField(widget=forms.Select,
                                                      initial="show",
                                                      required=False,
                                                      label="On New Notifications")
    timeout = forms.IntegerField(min_value = 5,
                                 max_value = 3600,
                                 initial=30,
                                 required=False,
                                 label="Timeout (in seconds)",
                                 help_text="Used only if Acknowledgement Type is set to 'timeout'")

    def __init__(self, request, *args, **kwargs):
        super(ToastNotificationConfigForm, self).__init__(*args, **kwargs)

        prefs = request.user.prefs

        if hasattr(prefs, 'toast_notifications'):
            for k in prefs.toast_notifications: