# VERSION: 1.0
# AUTHORS: Naru
#
# Internet Archive (archive.org) search plugin.
# 공개 도메인 / 크리에이티브 커먼즈 등 합법 콘텐츠만 색인하는 archive.org 를
# 검색한다. 각 아이템은 archive.org 가 직접 시딩하는 .torrent 로 제공된다.

import json
from urllib.parse import quote

from helpers import retrieve_url
from novaprinter import prettyPrinter


class internetarchive:
    url = 'https://archive.org'
    name = 'Internet Archive'
    supported_categories = {'all': ''}

    def search(self, what: str, cat: str = 'all') -> None:
        query = what.replace('+', ' ')
        api = (
            'https://archive.org/advancedsearch.php?q='
            + quote('(' + query + ') AND mediatype:(movies OR audio OR texts OR software OR data OR image)')
            + '&fl[]=identifier&fl[]=title&fl[]=item_size&fl[]=downloads'
            + '&sort[]=downloads+desc&rows=60&page=1&output=json'
        )
        try:
            data = json.loads(retrieve_url(api))
        except Exception:
            return

        for doc in data.get('response', {}).get('docs', []):
            ident = doc.get('identifier')
            if not ident:
                continue
            title = doc.get('title', ident)
            if isinstance(title, list):
                title = title[0] if title else ident
            size = doc.get('item_size', 0) or 0
            torrent = 'https://archive.org/download/{0}/{0}_archive.torrent'.format(ident)
            prettyPrinter({
                'link': torrent,
                'name': str(title),
                'size': str(size) + ' B',
                'seeds': -1,
                'leech': -1,
                'engine_url': self.url,
                'desc_link': 'https://archive.org/details/' + ident,
            })
