# Path: oxidizr/apps/keywords/models.py
# class BaseKeyword(models.Model):
#     """
#     This model holds all the keywords in the system. Best efforts are made to keep this list clean.
#     Text is cleaned using various methods to mitigate mistakes.
# 
#     Keywords must follow these rules:
#     * can be only in lower case.
#     * may not have a comma (multiple keywords not allowed)
#     """
#     term = models.CharField(max_length=60, blank=False, null=False, unique=True)
# 
#     def __str__(self):
#         return '%s' % self.term
# 
#     def __unicode__(self):
#         return u'%s' % self.term
# 
# class Keyword(models.Model):
#     """
#     This model holds the keyword data, related per affiliate.
#     Also for every (keyword, affiliate) pair there are settings for the actual usage of the keywords.
# 
#     The settings allow users to control how the keywords play in search filtering.
#     """
#     base = models.ForeignKey('keywords.BaseKeyword', related_name='+')
#     project = models.ForeignKey('projects.Project', related_name='keywords')
# 
#     # What is the importance of this keyword to this project, more means higher importance.
#     weight = models.PositiveIntegerField(default=0)
# 
#     # This meta contains JSON encoded status for each application that needs keywords to filter search results
#     # TODO: Parse this in the management commands for twitter, meetup, etc.
#     # TODO: Allow keywords to be combined in search filter. Basically keyword dependencies.
#     status_settings_meta = models.CharField(max_length=500, blank=True, null=True)
# 
#     class Meta:
#         unique_together = ['base', 'project']
# 
#     def __str__(self):
#         return '%s' % self.base.term
# 
#     def __unicode__(self):
#         return u'%s' % self.base.term
# 
# Path: oxidizr/apps/keywords/forms.py
# class KeywordCreateForm(forms.Form):
#     term = forms.CharField(max_length=60, required=True)
# 
#     def __init__(self, *args, **kwargs):
#         super(KeywordCreateForm, self).__init__(*args, **kwargs)
#         self.helper = FormHelper()
#         self.helper.form_id = 'id_form_keywords_create'
#         self.helper.layout = Layout(
#             Div(
#                 Div(
#                     'term',
#                     css_class='col-sm-6 col-sm-offset-3'
#                 ),
#                 css_class='row'
#             ),
#             HTML('''<hr class="full">'''),
#             Div(
#                 Div(
#                     HTML('''<a href="{% url 'keywords_manage' %}">{{ _('Cancel') }}</a>&nbsp;&nbsp;'''),
#                     Submit('submit', _('Save'), css_class='btn-success btn-lg'),
#                     css_class='pull-right'
#                 ),
#                 css_class='row',
#             )
#         )
# 
#     def clean_term(self):
#         term = self.cleaned_data['term']
#         return term.strip().lower().replace(',', '')


from django.views.generic import View, TemplateView, ListView, FormView
from django.core.urlresolvers import reverse_lazy
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from django.http.response import HttpResponseRedirect
from django.db.utils import IntegrityError
from braces.views import LoginRequiredMixin, JSONResponseMixin, UserPassesTestMixin
from apps.common.utils import not_logged_in_error_message, project_not_set_error_message
from .models import BaseKeyword, Keyword
from .forms import KeywordCreateForm
    context_object_name = 'keywords'

    def get_queryset(self):
        if self.request.project:
            return Keyword.objects.filter(project=self.request.project)
        else:
            return None


class KeywordCreateView(LoginRequiredMixin, UserPassesTestMixin, FormView):
    model = Keyword
    form_class = KeywordCreateForm
    template_name = 'keywords/create.html'
    success_url = reverse_lazy('keywords_manage')

    def test_func(self, user):
        if self.request.project:
            return True
        return False

    def get_login_url(self):
        if not self.request.user.is_authenticated():
            not_logged_in_error_message(self.request)
            return reverse_lazy('accounts_login')
        if not self.request.project:
            project_not_set_error_message(self.request)
            return reverse_lazy('projects_index')

    def form_valid(self, form):
        base, created = BaseKeyword.objects.get_or_create(term=form.cleaned_data['term'])

# Path: oxidizr/apps/keywords/models.py
# class BaseKeyword(models.Model):
#     """
#     This model holds all the keywords in the system. Best efforts are made to keep this list clean.
#     Text is cleaned using various methods to mitigate mistakes.
# 
#     Keywords must follow these rules:
#     * can be only in lower case.
#     * may not have a comma (multiple keywords not allowed)
#     """
#     term = models.CharField(max_length=60, blank=False, null=False, unique=True)
# 
#     def __str__(self):
#         return '%s' % self.term
# 
#     def __unicode__(self):
#         return u'%s' % self.term
# 
# class Keyword(models.Model):
#     """
#     This model holds the keyword data, related per affiliate.
#     Also for every (keyword, affiliate) pair there are settings for the actual usage of the keywords.
# 
#     The settings allow users to control how the keywords play in search filtering.
#     """
#     base = models.ForeignKey('keywords.BaseKeyword', related_name='+')
#     project = models.ForeignKey('projects.Project', related_name='keywords')
# 
#     # What is the importance of this keyword to this project, more means higher importance.
#     weight = models.PositiveIntegerField(default=0)
# 
#     # This meta contains JSON encoded status for each application that needs keywords to filter search results
#     # TODO: Parse this in the management commands for twitter, meetup, etc.
#     # TODO: Allow keywords to be combined in search filter. Basically keyword dependencies.
#     status_settings_meta = models.CharField(max_length=500, blank=True, null=True)
# 
#     class Meta:
#         unique_together = ['base', 'project']
# 
#     def __str__(self):
#         return '%s' % self.base.term
# 
#     def __unicode__(self):
#         return u'%s' % self.base.term
# 
# Path: oxidizr/apps/keywords/forms.py
# class KeywordCreateForm(forms.Form):
#     term = forms.CharField(max_length=60, required=True)
# 
#     def __init__(self, *args, **kwargs):
#         super(KeywordCreateForm, self).__init__(*args, **kwargs)
#         self.helper = FormHelper()
#         self.helper.form_id = 'id_form_keywords_create'
#         self.helper.layout = Layout(
#             Div(
#                 Div(
#                     'term',
#                     css_class='col-sm-6 col-sm-offset-3'
#                 ),
#                 css_class='row'
#             ),
#             HTML('''<hr class="full">'''),
#             Div(
#                 Div(
#                     HTML('''<a href="{% url 'keywords_manage' %}">{{ _('Cancel') }}</a>&nbsp;&nbsp;'''),
#                     Submit('submit', _('Save'), css_class='btn-success btn-lg'),
#                     css_class='pull-right'
#                 ),
#                 css_class='row',
#             )
#         )
# 
#     def clean_term(self):
#         term = self.cleaned_data['term']
#         return term.strip().lower().replace(',', '')


# Path: oxidizr/apps/keywords/views.py
from django.views.generic import View, TemplateView, ListView, FormView
from django.core.urlresolvers import reverse_lazy
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from django.http.response import HttpResponseRedirect
from django.db.utils import IntegrityError
from braces.views import LoginRequiredMixin, JSONResponseMixin, UserPassesTestMixin
from apps.common.utils import not_logged_in_error_message, project_not_set_error_message
from .models import BaseKeyword, Keyword
from .forms import KeywordCreateForm

    context_object_name = 'keywords'

    def get_queryset(self):
        if self.request.project:
            return Keyword.objects.filter(project=self.request.project)
        else:
            return None


class KeywordCreateView(LoginRequiredMixin, UserPassesTestMixin, FormView):
    model = Keyword
    form_class = KeywordCreateForm
    template_name = 'keywords/create.html'
    success_url = reverse_lazy('keywords_manage')

    def test_func(self, user):
        if self.request.project:
            return True
        return False

    def get_login_url(self):
        if not self.request.user.is_authenticated():
            not_logged_in_error_message(self.request)
            return reverse_lazy('accounts_login')
        if not self.request.project:
            project_not_set_error_message(self.request)
            return reverse_lazy('projects_index')

    def form_valid(self, form):
        base, created = BaseKeyword.objects.get_or_create(term=form.cleaned_data['term'])

        keyword = Keyword()