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

# %% auto 0
__all__ = ['Component', 'Media', 'IIIFImage', 'UrlImage', 'Part', 'ListPart', 'ListExternalLinkPart', 'JpsCurationTimeline',
           'JpsCurationTimepoint', 'JpsCurationText', 'JpsCurationList', 'JPSGalleryClient']

# %% ../api.ipynb 3
from pprint import pprint
import os
import json
import base64
import time

# %% ../api.ipynb 4
class Component:

    item = {
        "parts": []
    }
    
    def export(self):
        '''
        エクスポート

        Returns:  
        * dict containing representation of the gallery
        '''
        return self.item

    def setLangMetadata(self, key, lang, value):
        '''
        メタデータの設定

        Parameters:  
        * `key` - title, description, etc...  
        * `lang` - one of 言語, eg: 'ja', 'en', 'yomi'  
        * `value` - 値
        '''
        item = self.item
        if key not in item:
            item[key] = {}
        item[key][lang] = value

    def setMetadata(self, key, data):
        self.item[key] = data

    def addPart(self, part):
        '''
        パーツの追加
        
        Parameters:
        * `part` - パーツ        
        '''
        item = self.item
        if 'parts' not in item:
            item['parts'] = []
        item["parts"].append(part.export())  

class Media(Component):

    def __init__(self, type, title, source):
        self.item = {
            "imgType": type,
            "cover": None,
            "sourceUrl": None,
            "title": {
                "ja": title
            },
            "source": {
                "ja": source
            },
            "contentsRightsType": "various",
        }

class IIIFImage(Media):
    def __init__(self, manifestUrl, infoJsonUrl, title, source, xywh=None):
        super().__init__("IIIF", title, source)

        item = self.item
        item["cover"] = None
        item["sourceUrl"] = None
        item["manifestUrl"] = manifestUrl
        item["infoJsonUrl"] = infoJsonUrl

        if xywh is not None:
            spl = xywh.split(',')
            item["x"] = int(spl[0])
            item["y"] = int(spl[1])
            item["w"] = int(spl[2])
            item["h"] = int(spl[3])

class UrlImage(Media):
    """
    URLを指定して表示する画像に関するクラス
    """

    def __init__(self, url, title, source, thumbnailUrl=None):
        """
        初期化

        Parameters:  
        * `url` - 画像URL  
        * `title` - 日本語のタイトル  
        * `source` - 日本語の出典  
        * `thumbnailUrl` - サムネイルURL
        """
        super().__init__("URL", title, source)

        item = self.item

        item["url"] = url
        if thumbnailUrl is not None:
            item["thumbnailUrl"] = thumbnailUrl



class Part(Component):

    def __init__(self, type): # , viewType
        item = {}
        self.item = item
        item["cpid"] = "a"
        item["type"] = type

    def addText(self, lang, value):
        '''
        opsに要素を追加します。

        Parameters:  
        * `lang` - one of 言語, eg: 'ja', 'en', 'yomi'  
        * `value` - 値
        '''
        item = self.item

        ops = item[lang]["ops"]
        ops.append({
            "insert": value
        })
        ops.append({
            "insert": "\n"
        })

    def setUrl(self, url):
        '''
        外部リンクのURLを設定します。

        Parameters:  
        * `url` - 外部リンクのURL
        '''
        self.item["url"] = url 

    def setImage(self, image):
        self.item["image"] = image.export()

class ListPart(Part):
    '''
    リストパーツ
    '''
    def __init__(self, viewType):
        '''
        初期化

        Parameters:  
        * `viewType` - レイアウト, eg: 'tile', 'table', etc...
        '''
        # super().__init__("list") # , viewType
        super().__init__("jps-curation-list") # , viewType

        item = self.item
        item["viewType"] = viewType

class ListExternalLinkPart(Part):
    '''
    ListExternalLinkPart
    '''
    
    def __init__(self):
        '''
        初期化
        '''
        super().__init__("jps-curation-list-external-link")

class JpsCurationTimeline(Part):
    '''
    JpsCurationTimeline
    '''
    
    def __init__(self, start, end, layout="bar"):
        '''
        初期化
        '''
        super().__init__("jps-curation-timeline")

        item = self.item
        item["timeline"] = {
            "start": start,
            "end": end,
        }
        item["layout"] = layout

class JpsCurationTimepoint(Part):
    '''
    JpsCurationTimepoint
    '''
    
    def __init__(self, name_ja, name_en, start, end, startFraction=0, endFraction=0, labelHeight=1):
        '''
        初期化
        '''
        super().__init__("jps-curation-timepoint")

        item = self.item
        item["time"] = {
            "name": {
                "ja": name_ja,
                "en": name_en,
            },
            "start": start,
            "end": end,
            "startFraction": startFraction,
            "endFraction": endFraction,
            "labelHeight": labelHeight
        }

class JpsCurationText(Part):
    '''
    JpsCurationText
    '''
    
    def __init__(self):
        '''
        初期化
        '''
        super().__init__("jps-curation-text")

        item = self.item
        item["ja"] = {
            "ops": []
        }

        item["en"] = {
            "ops": []
        }

class JpsCurationList(Part):
    '''
    リストパーツ
    '''
    def __init__(self, viewType):
        '''
        初期化

        Parameters:  
        * `viewType` - レイアウト, eg: 'tile', 'table', etc...
        '''
        # super().__init__("list") # , viewType
        super().__init__("jps-curation-list") # , viewType

        item = self.item

        item["viewType"] = viewType

        item["parts"] = []

class JPSGalleryClient(Part):

    def __init__(self, curationType="GALLERY", version=1, rightsType="ccby"):
        date = int(time.time() * 1000) 
        item = {
            "version": version,
            # "seqNo": 0,
            # "primaryTerm": 1,
            # "curationType": curationType,
            "title": {},
            "summary": {},
            "responsibility": {},
            # "workspace": "abc",
            "workspaceTags": [],
            "permission": {
                # "publicationLevel": "WORKSPACE",
                # "level": "ADMIN"
            },
            "edit": {
                "userId": "system",
                "orgId": "jpsws",
                "date": date,
                "action": "CREATE"
            },
            "parts": [],
            "rights": {},
            "rightsType": rightsType,
        }
        # item["id"] = "aaa"
        item["curationType"] = curationType

        self.item = item

    '''
    def setTitle(self, key, value):
        self.item["title"][key] = value

    def setSummary(self, key, value):
        self.item["summary"][key] = value
    '''

    def setTheme(self, theme):
        self.item["theme"] = theme

    def addTag(self, tag):
        '''
        タグを追加します。

        Parameters:  
        * `tag` - タグ
        '''
        item = self.item
        item["workspaceTags"].append(tag)

    '''
    def setImage(self, image):
        self.item["image"] = image.export()
    '''

    def saveJsonl(self, path):
        '''
        JSONLファイルの保存

        Parameters:  
        * `path` - 出力先のパス
        '''

        arr = []
        arr.append(json.dumps(self.item, ensure_ascii=False))

        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, mode='w') as f:
            f.write("\n".join(arr))

    def save(self, path):
        '''
        JSONファイルの保存

        Parameters:  
        * `path` - 出力先のパス
        '''
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, 'w') as f:
            json.dump(self.item, f, ensure_ascii=False, indent=2)

    def encode(self, curationType="NOTE"):
        '''
        Base64エンコード

        Returns:  
        * str containing Base64 encoded representation of the gallery
        '''
        item = self.item
        item["curationType"] = curationType # "NOTE"
        json_string = json.dumps(item)
        return base64.b64encode(json_string.encode('utf-8')).decode('utf-8')
