import traceback
from my_utils import request_post, filter_video_status, filter_video_status_app
from db_helper import RedisHelper
from my_config import set_config
from log import Log

config_, _ = set_config()
log_ = Log()


def get_top_video_list():
    """接口获取生效中的置顶视频列表，并存入redis"""
    try:
        result = request_post(request_url=config_.TOP_VIDEO_LIST_URL, request_data={})
        if result is None:
            return
        if result['code'] != 0:
            log_.info('获取置顶视频失败！')
            return

        data = result['data']
        if len(data) == 0:
            log_.info('无置顶视频！')
            return

        # 视频状态过滤
        video_ids = [item['videoId'] for item in data]
        log_.info('video_ids = {}'.format(video_ids))
        filter_videos = filter_video_status(video_ids=video_ids)
        log_.info('filter_videos = {}'.format(filter_videos))
        value = [item for item in data if item['videoId'] in filter_videos]
        log_.info('value = {}'.format(value))
        # 写入redis
        redis_helper = RedisHelper()
        redis_helper.set_data_to_redis(key_name=config_.TOP_VIDEO_LIST_KEY_NAME, value=str(value), expire_time=5 * 60)
        log_.info('置顶视频更新成功！')

        # app推荐状态过滤
        app_filter_videos = filter_video_status_app(video_ids=video_ids)
        log_.info('app_filter_videos = {}'.format(app_filter_videos))
        app_value = [item for item in data if item['videoId'] in app_filter_videos]
        log_.info('app_value = {}'.format(app_value))
        # 写入redis
        redis_helper = RedisHelper()
        redis_helper.set_data_to_redis(key_name=config_.TOP_VIDEO_LIST_KEY_NAME_APP, value=str(app_value),
                                       expire_time=5 * 60)
        log_.info('置顶视频app更新成功！')

    except Exception as e:
        log_.error('置顶视频更新失败！')
        log_.error(traceback.format_exc())


if __name__ == '__main__':
    get_top_video_list()
