From a52cbd992ed8369edd59fc181c48c27540d7a494 Mon Sep 17 00:00:00 2001
From: Yoann Schneider <yschneider@teklia.com>
Date: Mon, 3 Oct 2022 09:23:48 +0200
Subject: [PATCH] polygon shortcut

---
 arkindex_worker/models.py | 15 ++++++++++++++-
 tests/test_element.py     | 13 +++++++++++++
 2 files changed, 27 insertions(+), 1 deletion(-)

diff --git a/arkindex_worker/models.py b/arkindex_worker/models.py
index a29811db..ae6eb85f 100644
--- a/arkindex_worker/models.py
+++ b/arkindex_worker/models.py
@@ -5,7 +5,7 @@ Wrappers around API results to provide more convenient attribute access and IIIF
 
 import tempfile
 from contextlib import contextmanager
-from typing import Generator, Optional
+from typing import Generator, List, Optional
 
 from PIL import Image
 from requests import HTTPError
@@ -93,6 +93,19 @@ class Element(MagicDict):
             url += "/"
         return "{}full/{}/0/default.jpg".format(url, size)
 
+    @property
+    def polygon(self) -> List[float]:
+        """
+        Access an Element's polygon.
+        This is a shortcut to an Element's polygon, normally accessed via
+        its zone field via `zone.polygon`. This is mostly done
+        to facilitate access to this important field by matching
+        the [CachedElement][arkindex_worker.cache.CachedElement].polygon field.
+        """
+        if not self.get("zone"):
+            raise ValueError("Element {} has no zone".format(self.id))
+        return self.zone.polygon
+
     @property
     def requires_tiles(self) -> bool:
         """
diff --git a/tests/test_element.py b/tests/test_element.py
index 960d6eda..51e08b07 100644
--- a/tests/test_element.py
+++ b/tests/test_element.py
@@ -402,3 +402,16 @@ def test_setattr_setitem():
     element = Element({"name": "something"})
     element.type = "page"
     assert dict(element) == {"name": "something", "type": "page"}
+
+
+def test_element_polygon():
+    element = Element(
+        {"zone": {"polygon": [[0, 0], [181, 0], [181, 240], [0, 240], [0, 0]]}}
+    )
+    assert element.polygon == [[0, 0], [181, 0], [181, 240], [0, 240], [0, 0]]
+
+
+def test_element_no_polygon():
+    element = Element(id="element_id")
+    with pytest.raises(ValueError, match="Element element_id has no zone"):
+        _ = element.polygon
-- 
GitLab