from pydantic import BaseModel, Extra
from ichec_django_core.client import (
    Timestamped,
    FormCreate,
    FormDetail,
    FormFieldDetail,
    register_types,
    PopulatedFormCreate,
    PopulatedFormDetail,
)


class License(BaseModel, frozen=True):
    full_name: str
    identifier: str
    uri: str
    fsf_approved: bool = False
    osi_approved: bool = False
    vocab_url: str | None = None
    full_text: str | None = None

    class Config:
        extra = Extra.forbid


class DatasetIdAuthority(BaseModel, frozen=True):
    name: str
    uri: str


class DatasetBase(BaseModel, frozen=True):

    title: str
    description: str = ""
    uri: str | None = None
    is_public: bool = True
    access_instructions: str | None = None
    equipment: str | None = None
    facility: str | None = None
    template: str | None = None
    license: str | None = None
    id_authority: str | None = None
    parent: str | None = None
    tags: list[str] = []


class PrimitiveFormFieldValue(BaseModel, frozen=True):
    field: str
    value: str


class PrimitivePopulatedForm(BaseModel, frozen=True):
    values: list[PrimitiveFormFieldValue] = []


class DatasetCreate(DatasetBase, frozen=True):

    form: PopulatedFormCreate | None = None

    class Config:
        extra = Extra.forbid


class DatasetDetail(Timestamped, DatasetBase, frozen=True):

    form: PopulatedFormDetail | None
    creator: str

    class Config:
        extra = Extra.forbid


class DatasetList(DatasetDetail, frozen=True):
    class Config:
        extra = Extra.forbid


class DatasetTemplateBase(BaseModel, frozen=True):

    title: str
    description: str = ""
    uri: str | None = None


class DatasetTemplateCreate(DatasetTemplateBase, frozen=True):

    form: FormCreate

    class Config:
        extra = Extra.forbid


class DatasetTemplateDetail(Timestamped, DatasetTemplateBase, frozen=True):

    form: FormDetail
    creator: str

    class Config:
        extra = Extra.forbid

    def get_field(self, key: str) -> FormFieldDetail | None:
        for group in self.form.groups:
            for field in group.fields:
                if field.key == key:
                    return field
        return None


class DatasetTemplateList(DatasetTemplateDetail, frozen=True):
    class Config:
        extra = Extra.forbid


register_types(
    "datasets",
    {"create": DatasetCreate, "detail": DatasetDetail, "list": DatasetList},
)

register_types(
    "dataset_templates",
    {"create": DatasetTemplateCreate, "detail": DatasetTemplateDetail},
)
