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

_ADDON = xbmcaddon.Addon()


class SpiderDouYuLive(Spider):

    def name(self):
        return '斗鱼直播'

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

    def hide(self):
        return not _ADDON.getSettingBool('data_source_douyu_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://www.douyu.com/directory')
            m = re.search(r"DATA = (.*);", r.text, re.MULTILINE)
            data = json.loads(m.group(1))

            items = []
            for category in data['baseRecommendCategory']:
                items.append(
                    SpiderItem(
                        type=SpiderItemType.Directory,
                        name=category['cate2Name'],
                        id=category['cate2Id'],
                        params={
                            'type': 'category',
                        },
                    ))
            return items, False
        elif parent_item['params']['type'] == 'category':
            r = requests.get(
                'https://www.douyu.com/gapi/rkc/directory/mixList/2_{}/{}'.
                format(parent_item['id'], page))
            data = r.json()

            items = []
            for room in data['data']['rl']:
                if room['type'] != 1:
                    continue

                items.append(
                    SpiderItem(type=SpiderItemType.File,
                               id=room['rid'],
                               name='{} - {}'.format(
                                   room['rn'],
                                   room['nn'],
                               ),
                               description='主播: {}\n分类: {}'.format(
                                   room['nn'],
                                   room['c2name'],
                               ),
                               cover=room['rs1'],
                               sources=[
                                   SpiderSource(
                                       room['rid'],
                                       {
                                           'id': room['rid'],
                                       },
                                   )
                               ]))

            return items, page < data['data']['pgcnt']
        else:
            return [], False

    def resolve_play_url(self, source_params):
        return SpiderPlayURL('http://epg.112114.xyz/douyu/{}'.format(
            source_params['id']))

    def search(self, keyword):
        r = requests.get('https://www.douyu.com/japi/search/api/searchShow',
                         params={
                             'kw': keyword,
                             'page': 1,
                             'pageSize': 10,
                         })
        data = r.json()

        items = []
        for room in data['data']['relateShow']:
            items.append(
                SpiderItem(type=SpiderItemType.File,
                           id=room['rid'],
                           name='{} - {}'.format(
                               room['roomName'],
                               room['nickName'],
                           ),
                           description='主播: {}\n分类: {}'.format(
                               room['nickName'],
                               room['cateName'],
                           ),
                           cover=room['roomSrc'],
                           sources=[
                               SpiderSource(
                                   room['rid'],
                                   {
                                       'id': room['rid'],
                                   },
                               )
                           ]))

        return items
