""" 
Copyright 2016, 2017 UFPE - Universidade Federal de Pernambuco
 
Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS
 
O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença.
 
Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes.
 
Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENSE", junto com este programa, se não, escreva para a Fundação do Software Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA.
"""
from django.test import TestCase

from datetime import datetime, timedelta

import base64 
from django.utils.translation import ugettext_lazy as _, pgettext_lazy
from django.core.files.uploadedfile import InMemoryUploadedFile
from io import BytesIO 

from webpage.models import Webpage

from mural.forms import GeneralPostForm, SubjectPostForm, CommentForm

#Import factories
from categories.factories import RandomCategoryFactory
from subjects.factories import RandomSubjectFactory
from topics.factories import RandomTopicFactory
from users.factories import RandomUserFactory

TEST_IMAGE = '''
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBI
WXMAAABIAAAASABGyWs+AAAACXZwQWcAAAAQAAAAEABcxq3DAAABfElEQVQ4y52TvUuCURTGf5Zg
9goR9AVlUZJ9KURuUkhIUEPQUIubRFtIJTk0NTkUFfgntAUt0eBSQwRKRFSYBYFl1GAt901eUYuw
QTLM1yLPds/zPD/uPYereYjHcwD+tQ3+Uys+LwCah3g851la/lf4qwKb61Sn3z5WFUWpCHB+GUGb
SCRIpVKqBkmSAMrqsViMqnIiwLx7HO/U+6+30GYyaVXBP1uHrfUAWvWMWiF4+qoOUJLJkubYcDs2
S03hvODSE7564ek5W+Kt+tloa9ax6v4OZ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vaU5psnHD/6mMF8jcqWwRgwpWOjKiLkQkOhv5+xsTLl
cpnR0WOUSiVEhLVKhbXXa7xcXqHyaoV6o0Hqd1MxUjqu7XYLMFkaNXtXYC09+R5UwbkYEcVaizFm
P/LWGsLJydMs3VvCWkP3gzxK7OKu7Bl81/tEhKmpKVhYWNCJiQkNglDDMKdhLpf1/0AQhDo+Pq5z
c3NKmqa6uLios7MXtFgsahRFGhUKHUS7KBQ0iiIdGhrS8+dndH5+XpMk0X8AMTVx/inpU4cAAAAl
dEVYdGNyZWF0ZS1kYXRlADIwMTAtMTItMjZUMTQ6NDk6MjErMDk6MDAHHBB1AAAAJXRFWHRtb2Rp
ZnktZGF0ZQAyMDEwLTEyLTI2VDE0OjQ5OjIxKzA5OjAwWK1mQQAAAABJRU5ErkJggg==
'''.strip()

class TestForm(TestCase):
    staff = None

    professors = None
    students = None

    categories = None
    subjects = None
    topics = None
    resources = []
    
    def setUp(self):
        self.create_users()
        self.create_categories()
        self.create_subjects()
        self.create_topics()
        self.create_resources()

    def create_users(self):
        self.staff = RandomUserFactory.create(is_staff=True)
        self.professors = RandomUserFactory.create_batch(3, is_staff=False)
        self.students = RandomUserFactory.create_batch(18, is_staff=False)

    def create_categories(self):
        self.categories = RandomCategoryFactory.create_batch(3)

    def create_subjects(self):
        self.subjects = RandomSubjectFactory.create_batch(5, category=self.categories[0], professor=(self.professors[0],), students=(self.students[0:5]))
        self.subjects += RandomSubjectFactory.create_batch(5, category=self.categories[1], professor=(self.professors[1],), students=(self.students[6:11]))
        self.subjects += RandomSubjectFactory.create_batch(5, category=self.categories[2], professor=(self.professors[2],), students=(self.students[12:17]))

    def create_topics(self):
        self.topics = RandomTopicFactory.create_batch(2, subject=self.subjects[1])

    def create_resources(self):
        self.resources = []
        self.resources.append(Webpage.objects.create(name="Recurso Teste", content="teste", topic=self.topics[0], visible=True))
        self.resources.append(Webpage.objects.create(name="Recurso Teste 2", content="teste", topic=self.topics[0], visible=True, all_students=False))

    def test_form_choices(self):
        form = GeneralPostForm()

        self.assertIn(("comment", pgettext_lazy("form","Comment")), form.fields["action"].choices)
        self.assertIn(("help", pgettext_lazy("form","Ask for Help")), form.fields["action"].choices)

    def test_form_post_error(self):
        form = GeneralPostForm(data={})

        self.assertEquals(form.errors["post"], [_('This field is required.')])

    def test_form_image_error(self):
        form_data = {
            "post": "test",
        }

        image = InMemoryUploadedFile(
            BytesIO(base64.b64decode(TEST_IMAGE)),
            field_name='tempfile',
            name='tempfile.png',
            content_type='image/png',
            size=11*1024*1024,
            charset='utf-8',
        )

        form = GeneralPostForm(data=form_data, files={"image": image})

        self.assertEquals(form.errors["image"], [_("The image is too large. It should have less than 10MB.")])

    def test_subject_form_resources_staff(self):
        form = SubjectPostForm(initial={"user": self.staff, "subject": self.subjects[1]})

        self.assertEquals(len(form.fields["resource"].choices), len(self.resources) + 1)
        self.assertIn((self.resources[0].id, str(self.resources[0])), form.fields["resource"].choices)
        self.assertIn((self.resources[1].id, str(self.resources[1])), form.fields["resource"].choices)

    def test_subject_form_resources_student(self):
        form = SubjectPostForm(initial={"user": self.students[0], "subject": self.subjects[1]})

        visible_resources = [x for x in self.resources if x.all_students == True]

        self.assertEquals(len(form.fields["resource"].choices), len(visible_resources) + 1)
        self.assertIn((visible_resources[0].id, str(visible_resources[0])), form.fields["resource"].choices)

    def test_comment_form_post_error(self):
        form = CommentForm(data={})

        self.assertEquals(form.errors["comment"], [_('This field is required.')])

    def test_comment_form_image_error(self):
        form_data = {
            "post": "test",
        }

        image = InMemoryUploadedFile(
            BytesIO(base64.b64decode(TEST_IMAGE)),
            field_name='tempfile',
            name='tempfile.png',
            content_type='image/png',
            size=11*1024*1024,
            charset='utf-8',
        )

        form = CommentForm(data=form_data, files={"image": image})

        self.assertEquals(form.errors["image"], [_("The image is too large. It should have less than 10MB.")])