import PIL

from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType

from ichec_django_core.models import Member, Organization, Address


def generate_image():
    return PIL.Image.linear_gradient("L")


def _add_member(name: str, groups: list[str] | None = None):
    member = Member.objects.create(username=name)

    if not groups:
        return member

    for group_name in groups:
        group = Group.objects.get(name=group_name)
        member.groups.add(group)
        member.save()
    return member


def setup_default_users_and_groups():

    for group in ("admins", "members", "regular_users"):
        Group.objects.create(name=group)

    regular_user = _add_member("regular_user")
    other_user = _add_member("other_user")

    member = _add_member("member", ["members"])
    other_member = _add_member("other_member", ["members"])

    admin = _add_member("admin_user", ["admins", "members"])

    return regular_user, other_user, member, other_member, admin


def add_group_permissions(group_name: str, model: type, permissions: list):

    group = Group.objects.get(name=group_name)
    content_type = ContentType.objects.get_for_model(model)
    for permission_name in permissions:
        permission = Permission.objects.get(
            codename=permission_name, content_type=content_type
        )
        group.permissions.add(permission)
    group.save()


def setup_default_address():
    return Address.objects.create(
        line1="123 Street",
        line2="123 Avenue",
        line3="123 District",
        city="Big City",
        region="Region",
        postcode="ABC123",
        country="IE",
    )


def setup_default_organizations(member):

    internal = Organization.objects.create(
        name="Test Org 1",
        acronym="TO1",
        email="email@testorg.com",
        description="description of org",
        address=setup_default_address(),
        website="www.org.org",
        public=False,
    )
    internal.members.add(member)

    public = Organization.objects.create(
        name="Test Org 2",
        acronym="TO2",
        email="email@testorg.com",
        description="description of org",
        address=setup_default_address(),
        website="www.org.org",
        public=True,
    )

    inactive = Organization.objects.create(
        name="Test Org 3",
        acronym="TO3",
        email="email@testorg.com",
        description="description of org",
        address=setup_default_address(),
        website="www.org.org",
        public=True,
        active=False,
    )

    return internal, public, inactive
