class EmailLoginForm(forms.Form):
    email = forms.EmailField(
        max_length=255,
        label='',
        widget=forms.TextInput(attrs={
            'placeholder': 'Email address',
            'class': 'form-control',
        })
    )

    def clean(self):
        cleaned_data = super(EmailLoginForm, self).clean()
        return cleaned_data class SpeakerForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SpeakerForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.add_input(Submit('submit', _('Submit')))

    class Meta:
        model = Speaker
        fields = ('desc', 'info', )
        widgets = {
            'desc': SummernoteInplaceWidget(),
        }
        labels = {
            'desc': _('Profile'),
            'info': _('Additional information'),
        } class ProgramForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ProgramForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.add_input(Submit('submit', _('Submit')))

    class Meta:
        model = Program
        fields = ('slide_url', 'video_url', 'is_recordable', 'desc', )
        widgets = {
            'desc': SummernoteInplaceWidget(),
        }
        labels = {
            'slide_url': _('Slide URL'),
            'video_url': _('Video URL'),
            'is_recordable': _('Photography and recording is allowed'),
            'desc': _('Description'),
        } def sendEmailToken(request, token):
    variables = Context({
        'request': request,
        'token': token,
    })
    html = get_template('mail/token_html.html').render(variables)
    text = get_template('mail/token_text.html').render(variables)

    msg = EmailMultiAlternatives(
        settings.EMAIL_LOGIN_TITLE,
        text,
        settings.EMAIL_SENDER,
        [token.email])
    msg.attach_alternative(html, "text/html")
    msg.send(fail_silently=False) class Room(models.Model):
    name = models.CharField(max_length=100)
    location = models.CharField(max_length=255, null=True, blank=True)
    desc = models.TextField(null=True, blank=True)

    def get_absolute_url(self):
        return reverse('room', args=[self.id])

    def __unicode__(self):
        return self.name class Program(models.Model):
    name = models.CharField(max_length=100, db_index=True)
    desc = models.TextField(null=True, blank=True)
    slide_url = models.CharField(max_length=255, null=True, blank=True)
    pdf_url = models.CharField(max_length=255, null=True, blank=True)
    video_url = models.CharField(max_length=255, null=True, blank=True)
    speakers = models.ManyToManyField(Speaker, blank=True)
    language = models.CharField(max_length=2,
                                choices=settings.LANGUAGES,
                                default='ko')

    date = models.ForeignKey(ProgramDate)
    rooms = models.ManyToManyField(Room, null=True, blank=True)
    times = models.ManyToManyField(ProgramTime)
    category = models.ForeignKey(ProgramCategory, null=True, blank=True)

    is_recordable = models.BooleanField(default=True)

    def get_absolute_url(self):
        return reverse('program', args=[self.id])

    def room(self):
        rooms = self.rooms.all()

        if rooms.count() == Room.objects.all().count():
            return ''

        return ', '.join([_.name for _ in self.rooms.all()])

    def begin_time(self):
        return self.times.all()[0].begin.strftime("%H:%M")

    def get_speakers(self):
        return ', '.join([_.name for _ in self.speakers.all()])
    get_speakers.short_description = u'Speakers'

    def get_times(self):
        times = self.times.all()
        return '%s - %s' % (times[0].begin.strftime("%H:%M"),
                            times[len(times) - 1].end.strftime("%H:%M"))

    def __unicode__(self):
        return self.name class ProgramDate(models.Model):
    day = models.DateField()

    def __unicode__(self):
        return _date(self.day, "Y-m-d (D)") class ProgramTime(models.Model):
    name = models.CharField(max_length=100)
    begin = models.TimeField()
    end = models.TimeField()

    def __unicode__(self):
        return '%s - %s / %s' % (self.begin, self.end, self.name) class ProgramCategory(models.Model):
    name = models.CharField(max_length=100, db_index=True)
    slug = models.SlugField(max_length=100, db_index=True)

    def __unicode__(self):
        return self.name class Speaker(models.Model):
    slug = models.SlugField(max_length=100, db_index=True)
    name = models.CharField(max_length=100, db_index=True)
    email = models.EmailField(max_length=255, db_index=True,
                              null=True, blank=True)
    image = models.ImageField(upload_to='speaker', null=True, blank=True)
    desc = models.TextField(null=True, blank=True)
    info = JSONField(blank=True, help_text=_('help-text-for-speaker-info'))

    class Meta:
        ordering = ['name']

    def get_badges(self, size_class=""):
        badge = \
            '<a class="btn btn-social {} btn-{}" href="{}" target="_blank">' \
            '<i class="fa fa-{}"></i>{}</a>'
        fa_replacement = {
            "homepage": "home",
            "blog": "pencil",
        }
        result = []
        for site, url in self.info.iteritems():
            result.append(badge.format(
                size_class,
                site, url,
                fa_replacement.get(site, site), site.capitalize()
            ))
        return '<div class="badges">{}</div>'.format(' '.join(result))

    def get_badges_xs(self):
        return self.get_badges("btn-xs")

    def get_absolute_url(self):
        return reverse('speaker', args=[self.slug])

    def get_image_url(self):
        if self.image:
            return self.image.url

        return static('image/anonymous.png')

    def __unicode__(self):
        return '%s / %s' % (self.name, self.slug) class Sponsor(models.Model):
    slug = models.SlugField(max_length=100, db_index=True)
    name = models.CharField(max_length=100, db_index=True)
    image = models.ImageField(upload_to='sponsor', null=True, blank=True)
    url = models.CharField(max_length=255, null=True, blank=True)
    desc = models.TextField(null=True, blank=True)
    level = models.ForeignKey(SponsorLevel, null=True)

    def get_absolute_url(self):
        return reverse('sponsor', args=[self.slug])

    def __unicode__(self):
        return self.name class Jobfair(models.Model):
    name = models.CharField(max_length=100, db_index=True)
    location = models.CharField(max_length=255, null=True, blank=True)
    sponsor = models.ForeignKey(Sponsor, null=True)
    desc = models.TextField(null=True, blank=True)

    def __unicode__(self):
        return self.name class Announcement(models.Model):
    title = models.CharField(max_length=100, db_index=True)
    desc = models.TextField(null=True, blank=True)

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-id']

    def __unicode__(self):
        return self.title class EmailToken(models.Model):
    email = models.EmailField(max_length=255)
    token = models.CharField(max_length=64, unique=True)
    created = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        self.token = str(uuid4())
        super(EmailToken, self).save(*args, **kwargs)
from django.conf import settings
from django.contrib.auth import login as user_login, logout as user_logout
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.utils.http import is_safe_url
from django.utils.translation import check_for_language
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, DetailView, UpdateView
from datetime import datetime, timedelta
from .forms import EmailLoginForm, SpeakerForm, ProgramForm
from .helper import sendEmailToken
from .models import (Room,
                     Program, ProgramDate, ProgramTime, ProgramCategory,
                     Speaker, Sponsor, Jobfair, Announcement,
                     EmailToken)


def index(request):
    return render(request, 'index.html', {
        'recent_announcements': Announcement.objects.all()[:3],
    })


def schedule(request):
    dates = ProgramDate.objects.all()
    times = ProgramTime.objects.all()
    rooms = Room.objects.all()

    wide = {}
    narrow = {}
    processed = set()
    for d in dates:
        wide[d] = {}
        narrow[d] = {}
        for t in times:
            wide[d][t] = {}
            narrow[d][t] = {}
            for r in rooms:
                s = Program.objects.filter(date=d, times=t, rooms=r)
                if s:
                    if s[0].times.all()[0] == t and s[0].id not in processed:
                        wide[d][t][r] = s[0]
                        narrow[d][t][r] = s[0]
                        processed.add(s[0].id)
                else:
                    wide[d][t][r] = None

            if len(narrow[d][t]) == 0:
                del(narrow[d][t])

    contexts = {
        'wide': wide,
        'narrow': narrow,
        'rooms': rooms,
    }
    return render(request, 'schedule.html', contexts)


class RoomDetail(DetailView):
    model = Room


class SponsorList(ListView):
    model = Sponsor


class SponsorDetail(DetailView):
    model = Sponsor


class SpeakerList(ListView):
    model = Speaker


class SpeakerDetail(DetailView):
    model = Speaker

    def get_context_data(self, **kwargs):
        context = super(SpeakerDetail, self).get_context_data(**kwargs)

        if self.request.user.is_authenticated():
            if self.request.user.email == self.object.email:
                context['editable'] = True

        return context


class SpeakerUpdate(UpdateView):
    model = Speaker
    form_class = SpeakerForm

    def get_queryset(self):
        queryset = super(SpeakerUpdate, self).get_queryset()
        return queryset.filter(email=self.request.user.email)


class ProgramList(ListView):
    model = ProgramCategory
    template_name = "pyconkr/program_list.html"


class ProgramDetail(DetailView):
    model = Program

    def get_context_data(self, **kwargs):
        context = super(ProgramDetail, self).get_context_data(**kwargs)

        if self.request.user.is_authenticated():
            for speaker in self.object.speakers.all():
                if self.request.user.email == speaker.email:
                    context['editable'] = True

        return context


class ProgramUpdate(UpdateView):
    model = Program
    form_class = ProgramForm

    def get_queryset(self):
        queryset = super(ProgramUpdate, self).get_queryset()
        return queryset.filter(speakers__email=self.request.user.email)


class JobfairList(ListView):
    model = Jobfair


class AnnouncementList(ListView):
    model = Announcement


class AnnouncementDetail(DetailView):

    model = Announcement