from spider_aliyundrive import SpiderAliyunDrive
from spider import SpiderItemType, SpiderItem
from bs4 import BeautifulSoup
from utils import get_image_path
import requests
import re
import xbmcaddon

_ADDON = xbmcaddon.Addon()


class SpiderZhaoZiYuan(SpiderAliyunDrive):

    regex_url = re.compile(r'https://www.aliyundrive.com/s/[^"]+')

    def name(self):
        return '找资源'

    def logo(self):
        return get_image_path('zhaoziyuan.png')

    def hide(self):
        return not _ADDON.getSettingBool('data_source_zhaoziyuan_switch')

    def is_searchable(self):
        return True

    def list_items(self, parent_item=None, page=1):
        if parent_item is None:
            return [], False

        if not parent_item['id'].startswith('http'):
            r = requests.get('https://zhaoziyuan.la/' + parent_item['id'])
            m = self.regex_url.search(r.text)
            url = m.group().replace('\\', '')
            parent_item['id'] = url
        return super().list_items(parent_item, page)

    def search(self, keyword):
        r = requests.get(
            'https://zhaoziyuan.la/so',
            params={
                'filename': keyword,
            },
        )
        r.encoding = 'utf8'
        soup = BeautifulSoup(r.text, 'html.parser')

        items = []
        elements = soup.select('div.news_text > a')
        for element in elements:
            name = element.find('h3').text
            items.append(
                SpiderItem(
                    type=SpiderItemType.Directory,
                    id=element.get('href'),
                    name=name,
                ))

        return items
