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

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

# %% ../nbs/pdf.ipynb 3
from urllib import request  # urllib.requestモジュールをインポート
from bs4 import BeautifulSoup  # BeautifulSoupクラスをインポート
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
def test():
    print("boo")

# %% ../nbs/pdf.ipynb 5
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):
        client = PdfClient()
        client.tmp_dir = input_dir
        client.create_pdf(outout_path, extension="jpg")
        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)

        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"]
            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)
        

    def get_infos(self, limit):
        response = request.urlopen(self.url)
        soup = BeautifulSoup(response, "html.parser")

        root = str(soup).split("var viewUrlRoot = '")[1].split("'")[0]
        self.root = root

        text = str(soup).split("var jsonUrls = [")[1].split("]")[0]
        items = text.replace("\"", "").split(",")

        infos = []

        if limit > 0:
            items = items[0:limit]
        
        for item in tqdm(items):

            page_url = root + item

            info_url = str(soup).split("var infoUrlRoot = '")[1].split("'")[0]
            url = info_url + item

            df = requests.get(url).json()

            # legacyの場合
            if "data" in df:
                levels = df["data"]["levels"]
                level = levels[-1]
                infos.append({
                    "width": level["width"],
                    "height": level["height"],
                    "url": level["url"]
                })
            else:
                infos.append(df)

        # return infos
        self.infos = infos

    def create_manifest(self):
        canvases = []

        infos = self.infos

        root = self.root[0:-1]

        for i, info in tqdm(enumerate(infos)):

            resource = {
                # '@id': info['@id'] + "/full/full/0/default.jpg",
                "@type": "dctypes:Image",
                "format": "image/jpeg",
                "height": info['height'],
                "width": info['width'],
                # "service": info,
            }

            if "url" in info:
                resource["@id"] = info["url"]
            else:
                resource["@id"] = info["@id"] + "/full/full/0/default.jpg"
                resource["service"] = info

            canvas = {
                '@id': "%s/canvas/p%d" % (root, i + 1),
                '@type': "sc:Canvas",
                'label': "[%d]" % (i+1),
                'width': info['width'],
                'height': info['height'],
                'images': [{
                    '@id': "%s/canvas/annotation/p%s-image" % (root, str(i+1).zfill(4)),
                    '@type': "oa:Annotation",
                    'motivation': "sc:Painting",
                    'resource': resource,
                    'on': "%s/canvas/p%d" % (root, i + 1),
                    }]

            }

            canvases.append(canvas)

        manifest = {
            '@context': 'http://iiif.io/api/presentation/2/context.json',
            '@id': root + "/manifest.json",
            '@type': 'sc:Manifest',
            'label': self.url,
            'sequences': [
                { 
                    '@id': root + '/sequence/normal',
                    '@type': 'sc:Sequence',
                    'canvases': canvases
                }
            ]
        }
        self.manifest = manifest

    def save(self):
        manifest = self.manifest

        path = self.path

        os.makedirs(os.path.dirname(path), exist_ok=True)

        with open(path, 'w') as f:
            json.dump(manifest, f, ensure_ascii=False, indent=4,
                    sort_keys=True, separators=(',', ': '))
