from ...common.enum import ParserType
from ...network.request import SyncNetWorkRequest
from ..episode.watch_later import WatchLaterEpisodeParser
from .base import ParserBase

import math

class WatchLaterParser(ParserBase):
    def __init__(self):
        super().__init__()

        self.ps = 20

    def parse(self, url: str, pn: int, get_info_data: bool = False):
        self.url = url
        self.pn = pn

        self.check_login()

        self.get_history_info()

        if get_info_data:
            return self.info_data

        episode_parser = WatchLaterEpisodeParser(self.info_data.copy(), self.get_category_name())
        episode_parser.parse()

    def get_history_info(self):
        params = {
            "pn": self.pn,
            "ps": self.ps,
            "viewed": 0,
            "key": "",
            "asc": False,
            "need_split": True,
            "web_location": "333.881"
        }

        url = f"https://api.bilibili.com/x/v2/history/toview/web?{self.enc_wbi(params)}"

        request = SyncNetWorkRequest(url, raise_for_status = self.raise_for_status)
        response = request.run()

        self.check_response(response)

        self.info_data = response

    def get_parser_type(self):
        return ParserType.WATCH_LATER
    
    def get_extra_data(self):
        count = self.info_data["data"]["count"]

        return {
            "pagination": True,
            "pagination_data": {
                "total_pages": math.ceil(count / self.ps),
                "total_items": count,
                "current_page": self.pn
            }
        }
