from pathlib import Path

from django.utils import timezone

from ichec_django_core.models import (
    Member,
    Form,
    FormGroup,
    FormField,
    PopulatedForm,
    FormFieldValue,
)

from ichec_django_core.test import add_group_permissions

from marinerg_test_access.models import AccessCall, AccessApplication


def setup_access_call():

    coordinator = Member.objects.create(
        username="access_call_coordinator",
        first_name="Access Call",
        last_name="Coordinator",
        email="access_call_coordinator@example.com",
    )
    access_call_board_member = Member.objects.create(
        username="access_call_board_member",
        first_name="Access Call",
        last_name="Board Member",
        email="access_call_board_member@example.com",
    )

    form = Form.objects.create()

    default_group = FormGroup.objects.create(form=form)

    FormField.objects.create(
        group=default_group,
        label="Sample Bool Field?",
        key="bool_field",
        required=True,
        field_type="BOOLEAN",
    )

    FormField.objects.create(
        group=default_group,
        label="Application Form",
        key="application_form",
        required=True,
        field_type="FILE",
    )

    access_call = AccessCall.objects.create(
        title="Test access call",
        description="Description of access call",
        status="OPEN",
        closing_date=timezone.now(),
        coordinator=coordinator,
        board_chair=access_call_board_member,
        form=form,
    )

    access_call.board_members.set([access_call_board_member])

    add_group_permissions("admins", AccessCall, ["change_accesscall", "add_accesscall"])
    return access_call


def setup_application(call, applicant="test_applicant", asset: Path | None = None):

    form = PopulatedForm.objects.create()

    FormFieldValue.objects.create(
        value="TRUE", field=call.get_field_by_key("bool_field"), form=form
    )

    if asset:
        file_field = FormFieldValue.objects.create(
            field=call.get_field_by_key("application_form"), form=form
        )
        file_field.asset.original_filename = asset.name
        file_field.asset.name = str(asset)
        file_field.save()

    applicant = Member.objects.create(
        username=applicant,
        first_name="Test",
        last_name="Applicant",
        email=applicant + "@example.com",
    )
    return AccessApplication.objects.create(applicant=applicant, call=call, form=form)
