import os
import random

import factory
import wagtail_factories
from django.conf import settings
from django.contrib.auth import get_user_model
from factory.django import ImageField, FileField
from faker import Faker
from wagtail.documents.models import get_document_model
from wagtail.images import get_image_model

from users.models import Role, UserRole

fake = Faker(['de_CH', 'en-US'])


def fake_title(x=None, min_words=2, max_words=4):
    return fake.sentence(nb_words=random.randint(min_words, max_words)).replace('.', '')


def fake_paragraph(x=None):
    return '<p>{}</p>'.format(fake_title())


class BasePageFactory(wagtail_factories.PageFactory):
    title = factory.LazyAttribute(fake_title)


class DummyDocumentFactory(factory.DjangoModelFactory):
    class Meta:
        model = get_document_model()

    title = factory.LazyAttribute(fake_title)
    file = FileField(
        from_path=os.path.join(settings.BASE_DIR, 'core', 'static', 'doc', 'dummy.pdf')
    )


class DummyImageFactory(factory.DjangoModelFactory):
    class Meta:
        model = get_image_model()

    title = factory.LazyAttribute(fake_title)
    file = ImageField(
        from_path=os.path.join(settings.BASE_DIR, 'core', 'static', 'img', 'dummy.jpg')
    )


class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = get_user_model()
        django_get_or_create = ('username',)

    first_name = factory.LazyAttribute(lambda x: fake.first_name())
    last_name = factory.LazyAttribute(lambda x: fake.last_name())
    email = factory.LazyAttribute(lambda x: fake.ascii_safe_email())
    hep_id = factory.Sequence(lambda n: n)

    @factory.post_generation
    def post(self, create, extracted, **kwargs):
        self.set_password('test')
        self.save()


class TeacherFactory(UserFactory):
    @factory.post_generation
    def post(self, create, extracted, **kwargs):
        Role.objects.create_default_roles()
        teacher_role = Role.objects.get_default_teacher_role()
        UserRole.objects.create(user=self, role=teacher_role)
