# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/api.ipynb.

# %% auto 0
__all__ = ['Client']

# %% ../nbs/api.ipynb 3
import requests
import json
from tqdm import tqdm
import os
import time
from urllib import request
import glob
from PIL import Image

# %% ../nbs/api.ipynb 4
class Client:
    "API client"
    def __init__(self):
        pass

    @staticmethod
    def downloadImagesFromManifest(manifest_url, output_dir, pos_start=1, pos_end=-1, sleep_time=0):
        # sleep_time = 0

        start = pos_start - 1
        end = pos_end

        df = requests.get(manifest_url).json()
        canvases = df["sequences"][0]["canvases"]

        urls = []

        for i in tqdm(range(len(canvases))):
            if i >= start and (end < 0 or i < end):
                pass
            else:
                continue

            res = canvases[i]["images"][0]["resource"]
            index = str(i+1).zfill(4)
            path = "{}/{}.jpg".format(output_dir, index)
            os.makedirs(os.path.dirname(path), exist_ok=True)
            url = canvases[i]["images"][0]["resource"]["@id"]
            time.sleep(sleep_time)
            request.urlretrieve(url, path)

            urls.append(url)

        return urls

    @staticmethod
    def convertBB(bbs):
        x_min = 100000
        y_min = 100000
        x_max = 0
        y_max = 0
        
        for bb in bbs:
            x = bb[0]
            y = bb[1]

            if x < x_min:
                x_min = x
            if x > x_max:
                x_max = x

            if y < y_min:
                y_min = y
            if y > y_max:
                y_max = y
        
        w = x_max - x_min
        h = y_max - y_min

        return "{},{},{},{}".format(x_min, y_min, w, h)

    @staticmethod
    def getAnnotations(path, canvas_uri):
        df = json.load(open(path, "r"))
        items = []

        for i in range(len(df[0])):
            index = i + 1
            item = df[0][i]

            text = item["text"]

            xywh = Client.convertBB(item["boundingBox"])

            

            items.append({
                "id": "{}/annos/{}".format(canvas_uri, index),
                "motivation": "commenting",
                "target": "{}#xywh={}".format(canvas_uri, xywh),
                "type": "Annotation",
                "body": {
                    "type": "TextualBody",
                    "value": text
                }
            })

        return items

    @staticmethod
    def createIIIFManifest3(output_path, urls, img_dir, json_path):
        json_files = glob.glob(json_path + "/*.json")
        json_files.sort()

        img_files = glob.glob(img_dir + "/*.jpg")
        img_files.sort()

        canvases = []

        for i in range(len(urls)):

            original = urls[i]

            if "/full/" in original and "/0/default" in original:
                isIIIF = True

            img = Image.open(img_files[i])
            width, height = img.size

            filename = os.path.basename(img_files[i]).split(".")[0]

            body = {
                "format": "image/jpeg",
                "height": height,
                "id": "{}".format(original),
                "type": "Image",
                "width": width
            }

            if isIIIF:
                body["service"] = [{
                    "type": "ImageService2",
                    "id": original.split("/full/")[0],
                    "profile": "level2"
                }]

            canvas = original

            items = [] # アノテーション

            items = Client.getAnnotations(json_files[i], canvas)

            page = {
                "annotations" : [
                    {
                        "id" : "{}/annos".format(canvas),
                        "items" : items,
                        "type": "AnnotationPage"
                    }
                ],
                "height": height,
                "id": "{}".format(canvas),
                "items": [
                    {
                        "id": "{}/page".format(canvas),
                        "items": [
                            {
                                "body": body,
                                "id": "{}/page/imageanno".format(canvas),
                                "motivation": "painting",
                                "target": "{}".format(canvas),
                                "type": "Annotation"
                            }
                        ],
                        "type": "AnnotationPage"
                    }
                ],
                "label" : {
                    "none": [
                        "[{}]".format(i+1)
                    ]
                },
                "type": "Canvas",
                "width": width
            }

            canvases.append(page)

        m_data = {
            "@context": [
                "http://iiif.io/api/presentation/3/context.json",
                "http://www.w3.org/ns.anno.jsonld"
            ],
            "id": original,
            "label": {
                "none": [
                    original
                ]
            },
            "behavior": [
                "individuals"
            ],
            "items": canvases,
            "type": "Manifest"
        }

        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        with open(output_path, 'w') as outfile:
            json.dump(m_data, outfile, ensure_ascii=False, indent=4,)


