1# =====================================================
2# Imports
3# =====================================================
4from typing import Annotated
5from xml.etree import cElementTree as et
6
7from pydantic import Field, PrivateAttr
8
9from mt_metadata.base import MetadataBase
10from mt_metadata.transfer_functions.io.emtfxml.metadata import helpers
11
12
13# =====================================================
14class Attachment(MetadataBase):
15 filename: Annotated[
16 str,
17 Field(
18 default="",
19 description="file name of the attached file data",
20 alias=None,
21 json_schema_extra={
22 "units": None,
23 "required": True,
24 "examples": ["example.zmm"],
25 },
26 ),
27 ]
28
29 description: Annotated[
30 str,
31 Field(
32 default="",
33 description="description of the attached file",
34 alias=None,
35 json_schema_extra={
36 "units": None,
37 "required": True,
38 "examples": ["The original used to produce the XML"],
39 },
40 ),
41 ]
42
43 _attachments: list = PrivateAttr(default_factory=list)
44
45 def read_dict(self, input_dict: dict) -> None:
46 """Read the input dictionary and populate the model fields."""
47 element_dict = {self._class_name: input_dict[self._class_name]}
48 if isinstance(element_dict[self._class_name], type(None)):
49 return
50 elif isinstance(element_dict[self._class_name], list):
51 for item in element_dict[self._class_name]:
52 attachment_item = Attachment() # type: ignore
53 if not self._class_name in item.keys():
54 item = {self._class_name: item}
55 attachment_item.from_dict(item)
56 self._attachments.append(attachment_item)
57
58 else:
59 self.from_dict(element_dict)
60
61 def to_xml(
62 self, string: bool = False, required: bool = True
63 ) -> str | et.Element | list[str] | list[et.Element]:
64 """
65
66 :param string: return as an XML string, defaults to False
67 :type string: bool, optional
68 :param required: whether the field is required, defaults to True
69 :type required: bool, optional
70 :return: the XML representation of the object
71 :rtype: str | list[str]
72
73 """
74
75 if self._attachments == []:
76 result = helpers.to_xml(
77 self,
78 string=string,
79 required=required,
80 order=["filename", "description"],
81 )
82 return result
83 else:
84 return [
85 helpers.to_xml(
86 item,
87 string=string,
88 required=required,
89 order=["filename", "description"],
90 )
91 for item in self._attachments
92 ] # type: ignore