from spider import Spider, SpiderItemType, SpiderSource, SpiderItem, SpiderPlayURL
from utils import get_image_path, remove_html_tags
import requests
import xbmcaddon

_ADDON = xbmcaddon.Addon()


class SpiderBiliBiliLive(Spider):

    def name(self):
        return 'BiliBili直播'

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

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

    def is_searchable(self):
        return True

    def list_items(self, parent_item=None, page=1):
        print(parent_item)
        if parent_item is None:
            r = requests.get(
                'https://api.live.bilibili.com/xlive/web-interface/v1/index/getWebAreaList',
                params={'source_id': 2})
            data = r.json()
            items = []
            for category in data['data']['data']:
                items.append(
                    SpiderItem(
                        type=SpiderItemType.Directory,
                        name=category['name'],
                        id=category['id'],
                        params={
                            'type': 'category',
                        },
                    ))
            return items, False
        elif parent_item['params']['type'] == 'category':
            r = requests.get(
                'https://api.live.bilibili.com/xlive/web-interface/v1/second/getList',
                params={
                    'platform': 'web',
                    'parent_area_id': parent_item['id'],
                    'page': page,
                })
            data = r.json()

            items = []
            for room in data['data']['list']:
                items.append(
                    SpiderItem(type=SpiderItemType.File,
                               id=room['roomid'],
                               name='{} - {}'.format(
                                   room['title'],
                                   room['uname'],
                               ),
                               description='主播: {}\n分类: {} - {}'.format(
                                   room['uname'],
                                   room['parent_name'],
                                   room['area_name'],
                               ),
                               cover=room['cover'],
                               sources=[
                                   SpiderSource(
                                       room['roomid'],
                                       {
                                           'id': room['roomid'],
                                       },
                                   )
                               ]))

            return items, data['data']['has_more']
        else:
            return [], False

    def resolve_play_url(self, source_params):
        r = requests.get('https://api.live.bilibili.com/room/v1/Room/playUrl',
                         params={
                             'cid': source_params['id'],
                             'qn': '20000',
                         })
        return SpiderPlayURL(r.json()['data']['durl'][0]['url'])

    def search(self, keyword):
        r = requests.get(
            'https://api.bilibili.com/x/web-interface/search/type',
            params={
                'page': 1,
                'page_size': 10,
                'order': 'online',
                'search_type': 'live',
                'keyword': keyword,
            },
            headers={'Cookie': 'buvid3=0'})
        data = r.json()

        items = []
        for room in data['data']['result']['live_room']:
            items.append(
                SpiderItem(type=SpiderItemType.File,
                           id=room['roomid'],
                           name='{} - {}'.format(
                               remove_html_tags(room['title']),
                               room['uname'],
                           ),
                           description='主播: {}\n分类: {}'.format(
                               room['uname'],
                               room['cate_name'],
                           ),
                           cover='https:' + room['cover'],
                           sources=[
                               SpiderSource(
                                   room['roomid'],
                                   {
                                       'id': room['roomid'],
                                   },
                               )
                           ]))

        return items
