# Path: festi/survey/models.py
# class Event(Base):
#     slug = models.SlugField(unique=True)
#     name = models.CharField(max_length=100, db_index=True)
#     props = JSONField(verbose_name='Questions', blank=True)
#     begin = models.DateTimeField()
#     end = models.DateTimeField()
#     is_public = models.BooleanField(default=False, db_index=True)
#     is_closed = models.BooleanField(default=True, db_index=True)
#     approve_email_content = models.TextField(blank=True, null=True, help_text=u'첫 줄은 제목')
# 
#     def __unicode__(self):
#         return self.name
# 
#     def as_dict(self):
#         return {
#             'id': self.id,
#             'name': self.name,
#             'props': self.props,
#             'begin': self.begin,
#             'end': self.end,
#         }
# 
#     def export_csv(self, f):
#         header = ['email', 'name', 'gender', 'is_approved', 'is_notified', 'is_attended']
# 
# 
#         f.write(BOM_UTF8)
#         writer = csv.writer(f)
#         writer.writerow([(col or '').encode('utf8') for col in header])
# 
#         for survey in self.survey_set.select_related('user').all():
#             try:
#                 social = survey.user.socialaccount_set.first()
#                 name = social.extra_data['name']
#                 gender = social.extra_data['gender']
#             except (AttributeError, KeyError):
#                 name = ''
#                 gender = ''
# 
#             row = [survey.user.email, name, gender, survey.is_approved, survey.is_notified, survey.is_attended]
#             row.extend([prop['answer'] for prop in survey.props])
#             writer.writerow([(col or '').encode('utf8') for col in row])
# 
#         return f
# 
# class Speaker(models.Model):
#     event = models.ForeignKey(Event)
#     idx = models.IntegerField(default=0)
#     name = models.CharField(max_length=100)
#     profile = models.CharField(max_length=100, blank=True)
#     profile_image = models.ImageField(upload_to=random_name)
#     keyword = models.CharField(max_length=20, blank=True)
#     topic = models.CharField(max_length=100, blank=True)
#     detail = models.TextField(blank=True)
# 
#     class Meta:
#         ordering = ('idx', 'id')
# 
# class Survey(Base):
#     event = models.ForeignKey(Event)
#     user = models.ForeignKey(settings.AUTH_USER_MODEL)
#     props = JSONField()
#     is_approved = models.BooleanField(default=False, db_index=True, verbose_name=u'승인여부')
#     is_notified = models.BooleanField(default=False, db_index=True, verbose_name=u'알림여부')
#     is_attended = models.BooleanField(default=False, db_index=True, verbose_name=u'참석여부')
# 
#     class Meta:
#         unique_together = (('event', 'user'),)
# 
#     def as_dict(self):
#         return {
#             'props': self.props,
#             'is_approved': self.is_approved,
#             'is_notified': self.is_notified,
#             'is_attended': self.is_attended,
#         }
# 
# Path: festi/survey/tasks.py
# @shared_task
# def event_notification(survey_id, subject, message, recipient_list):
#     send_mail(subject, message, None, recipient_list, fail_silently=False)
#     Survey.objects.filter(id=survey_id).update(is_notified=True)


from django.contrib import admin
from import_export import resources
from import_export.admin import ExportMixin
from .models import Event, Speaker, Survey
from .tasks import event_notification

    def user_detail(self, survey):
        return survey.user.email

    def props_detail(self, survey):
        return '\n\n'.join(u'Q : {question}\nA : {answer}'.format(**prop) for prop in survey.props)

    def send_approve_email(self, request, queryset):
        count = 0
        for survey in queryset:
            if survey.is_approved and survey.event.approve_email_content and survey.user.email:
                lines = survey.event.approve_email_content.strip().splitlines()
                title = lines[0]
                content = '\n'.join(lines[1:])
                event_notification.s(survey.id, title, content, [survey.user.email]).delay()
                count += 1
        if count == 0:
            self.message_user(request, u'전송할 유저가 없습니다.')
        else:
            self.message_user(request, u'{} 명의 유저에게 이메일을 전송 중입니다.'.format(count))
    send_approve_email.short_description = u'선택/승인된 survey 유저에게 승인메일 보내기'

    resource_class = SurveyResource

    def get_readonly_fields(self, request, obj=None):
        return ('event', 'user', 'props_detail')

    def has_add_permission(self, request):
        return False


# Path: festi/survey/models.py
# class Event(Base):
#     slug = models.SlugField(unique=True)
#     name = models.CharField(max_length=100, db_index=True)
#     props = JSONField(verbose_name='Questions', blank=True)
#     begin = models.DateTimeField()
#     end = models.DateTimeField()
#     is_public = models.BooleanField(default=False, db_index=True)
#     is_closed = models.BooleanField(default=True, db_index=True)
#     approve_email_content = models.TextField(blank=True, null=True, help_text=u'첫 줄은 제목')
# 
#     def __unicode__(self):
#         return self.name
# 
#     def as_dict(self):
#         return {
#             'id': self.id,
#             'name': self.name,
#             'props': self.props,
#             'begin': self.begin,
#             'end': self.end,
#         }
# 
#     def export_csv(self, f):
#         header = ['email', 'name', 'gender', 'is_approved', 'is_notified', 'is_attended']
# 
# 
#         f.write(BOM_UTF8)
#         writer = csv.writer(f)
#         writer.writerow([(col or '').encode('utf8') for col in header])
# 
#         for survey in self.survey_set.select_related('user').all():
#             try:
#                 social = survey.user.socialaccount_set.first()
#                 name = social.extra_data['name']
#                 gender = social.extra_data['gender']
#             except (AttributeError, KeyError):
#                 name = ''
#                 gender = ''
# 
#             row = [survey.user.email, name, gender, survey.is_approved, survey.is_notified, survey.is_attended]
#             row.extend([prop['answer'] for prop in survey.props])
#             writer.writerow([(col or '').encode('utf8') for col in row])
# 
#         return f
# 
# class Speaker(models.Model):
#     event = models.ForeignKey(Event)
#     idx = models.IntegerField(default=0)
#     name = models.CharField(max_length=100)
#     profile = models.CharField(max_length=100, blank=True)
#     profile_image = models.ImageField(upload_to=random_name)
#     keyword = models.CharField(max_length=20, blank=True)
#     topic = models.CharField(max_length=100, blank=True)
#     detail = models.TextField(blank=True)
# 
#     class Meta:
#         ordering = ('idx', 'id')
# 
# class Survey(Base):
#     event = models.ForeignKey(Event)
#     user = models.ForeignKey(settings.AUTH_USER_MODEL)
#     props = JSONField()
#     is_approved = models.BooleanField(default=False, db_index=True, verbose_name=u'승인여부')
#     is_notified = models.BooleanField(default=False, db_index=True, verbose_name=u'알림여부')
#     is_attended = models.BooleanField(default=False, db_index=True, verbose_name=u'참석여부')
# 
#     class Meta:
#         unique_together = (('event', 'user'),)
# 
#     def as_dict(self):
#         return {
#             'props': self.props,
#             'is_approved': self.is_approved,
#             'is_notified': self.is_notified,
#             'is_attended': self.is_attended,
#         }
# 
# Path: festi/survey/tasks.py
# @shared_task
# def event_notification(survey_id, subject, message, recipient_list):
#     send_mail(subject, message, None, recipient_list, fail_silently=False)
#     Survey.objects.filter(id=survey_id).update(is_notified=True)


# Path: festi/survey/admin.py
from django.contrib import admin
from import_export import resources
from import_export.admin import ExportMixin
from .models import Event, Speaker, Survey
from .tasks import event_notification


    def user_detail(self, survey):
        return survey.user.email

    def props_detail(self, survey):
        return '\n\n'.join(u'Q : {question}\nA : {answer}'.format(**prop) for prop in survey.props)

    def send_approve_email(self, request, queryset):
        count = 0
        for survey in queryset:
            if survey.is_approved and survey.event.approve_email_content and survey.user.email:
                lines = survey.event.approve_email_content.strip().splitlines()
                title = lines[0]
                content = '\n'.join(lines[1:])
                event_notification.s(survey.id, title, content, [survey.user.email]).delay()
                count += 1
        if count == 0:
            self.message_user(request, u'전송할 유저가 없습니다.')
        else:
            self.message_user(request, u'{} 명의 유저에게 이메일을 전송 중입니다.'.format(count))
    send_approve_email.short_description = u'선택/승인된 survey 유저에게 승인메일 보내기'

    resource_class = SurveyResource

    def get_readonly_fields(self, request, obj=None):
        return ('event', 'user', 'props_detail')

    def has_add_permission(self, request):
        return False


admin.site.register(Survey, SurveyAdmin)