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

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

# %% ../nbs/pdf.ipynb 3
import requests
from tqdm import tqdm
import json
import os
import urllib.error
import urllib.request
import datetime
import img2pdf
from PIL import Image
import shutil

# %% ../nbs/pdf.ipynb 4
class PdfClient:
    def __init__(self):

        dt = datetime.datetime.now()
        ts = datetime.datetime.timestamp(dt)

        tmp_dir = f"/tmp/iiif_pdf/{ts}"
        os.makedirs(tmp_dir, exist_ok=True)
        self.tmp_dir = tmp_dir
        pass

    @staticmethod
    def create_pdf_from_manifest_local(input_path, outout_path, limit=-1):
        client = PdfClient()
        with open(input_path) as f:
            manifest = json.load(f)
        client.download_images(manifest, limit)
        client.create_pdf(outout_path)
        shutil.rmtree(client.tmp_dir)

    @staticmethod
    def create_pdf_from_dir(input_dir, outout_path, extension="jpg"):
        input_dir = input_dir.rstrip("/")
        client = PdfClient()
        client.tmp_dir = input_dir
        client.create_pdf(outout_path, extension=extension)
        shutil.rmtree(client.tmp_dir)


    @staticmethod
    def create_pdf_from_manifest_url(manifest_url, outout_path, limit = -1):
        client = PdfClient()
        manifest = requests.get(manifest_url).json()
        client.download_images(manifest, limit)
        client.create_pdf(outout_path, extension="jpg")
        shutil.rmtree(client.tmp_dir)
        

    def create_pdf(self, output_path, extension="jpg"):
        pdf_FileName = output_path # "output.pdf" # 出力するPDFの名前
        png_Folder = self.tmp_dir + "/" # "/tmp/iiif_pdf/" # 画像フォルダ
        extension  = f".{extension}" # 拡張子がPNGのものを対象

        with open(pdf_FileName,"wb") as f:
            # 画像フォルダの中にあるPNGファイルを取得し配列に追加、バイナリ形式でファイルに書き込む
            f.write(img2pdf.convert([Image.open(png_Folder+j).filename for j in sorted(os.listdir(png_Folder))if j.endswith(extension)]))

    def download_images(self, manifest, limit): # input_path
        # with open(input_path) as f:
        #     manifest = json.load(f)

        context = manifest["@context"]

        if context == "http://iiif.io/api/presentation/2/context.json":

            canvases = manifest["sequences"][0]["canvases"]

            if limit > 0:
                canvases = canvases[0:limit]

            for i in tqdm(range(len(canvases))):
                canvas = canvases[i]
                resource = canvas["images"][0]["resource"]

                if "service" in resource:
                    url = resource["service"]["@id"] + "/full/full/0/default.jpg"
                else:
                    url = resource["@id"] #  + "/full/full/0/default.jpg"
                opath = self.tmp_dir + "/" + str(i).zfill(5) + ".jpg"
                self.download_image(url, opath)

        elif context == "http://iiif.io/api/presentation/3/context.json":
            canvases = manifest["items"]

            if limit > 0:
                canvases = canvases[0:limit]

            for i in tqdm(range(len(canvases))):
                canvas = canvases[i]
                resource = canvas["items"][0]["items"][0]["body"]

                if "service" in resource:
                    url = resource["service"]["id"] + "/full/full/0/default.jpg"
                else:
                    url = resource["id"] #  + "/full/full/0/default.jpg"
                opath = self.tmp_dir + "/" + str(i).zfill(5) + ".jpg"
                self.download_image(url, opath)

    def download_image(self, url, dst_path):
        # dst_path = self.tmp_dir + "/" + url.replace("/", "_")
        try:
            with urllib.request.urlopen(url) as web_file:
                data = web_file.read()
                with open(dst_path, mode='wb') as local_file:
                    local_file.write(data)
        except urllib.error.URLError as e:
            print(e)
