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

_ADDON = xbmcaddon.Addon()


class SpiderAliPanSou(SpiderAliyunDrive):

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

    def name(self):
        return '猫狸盘搜'

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

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

    def is_searchable(self):
        return True

    def list_items(self, parent_item=None, page=1):
        if parent_item is None:
            return [], False
        else:
            if not parent_item['id'].startswith('http'):
                url = 'https://www.alipansou.com/cv/' + parent_item[
                    'id'].split('/')[2]
                r = requests.get(
                    url,
                    headers={'referer': url},
                    allow_redirects=False,
                )
                parent_item['id'] = r.headers['Location']
            return super().list_items(parent_item, page)

    def search(self, keyword):
        r = requests.get('https://www.alipansou.com/search',
                         params={
                             'k': keyword,
                             't': 7,
                         })
        soup = BeautifulSoup(r.text, 'html.parser')

        rows = soup.select('van-row > a')
        items = []
        for row in rows:
            name = remove_html_tags(row.find('template').__str__())
            items.append(
                SpiderItem(
                    type=SpiderItemType.Directory,
                    name=name,
                    id=row.get('href'),
                ))

        return items
