# VERSION: 1.0
# AUTHORS: Naru
#
# Academic Torrents (academictorrents.com) search plugin.
# 학술·연구용 데이터셋을 공유하는 합법 플랫폼. 전체 목록(database.xml)을 받아
# 로컬에서 검색어로 필터링한다. (사이트가 직접 시딩)

import xml.etree.ElementTree as ET

from helpers import retrieve_url
from novaprinter import prettyPrinter


class academictorrents:
    url = 'https://academictorrents.com'
    name = 'Academic Torrents'
    supported_categories = {'all': ''}

    def search(self, what: str, cat: str = 'all') -> None:
        terms = [t for t in what.replace('+', ' ').lower().split() if t]
        try:
            root = ET.fromstring(retrieve_url('https://academictorrents.com/database.xml'))
        except Exception:
            return

        for item in root.iter('item'):
            title = (item.findtext('title') or '').strip()
            infohash = (item.findtext('infohash') or '').strip()
            if not infohash or not title:
                continue
            haystack = title.lower()
            if terms and not all(t in haystack for t in terms):
                continue
            size = (item.findtext('size') or '0').strip() or '0'
            prettyPrinter({
                'link': 'https://academictorrents.com/download/{0}.torrent'.format(infohash),
                'name': title,
                'size': size + ' B',
                'seeds': -1,
                'leech': -1,
                'engine_url': self.url,
                'desc_link': 'https://academictorrents.com/details/' + infohash,
            })
