from ....common.config import config
from ....format.time import Time

ass_base = """[Script Info]
; Script generated by Bili23 Downloader
; http://bili23.scott-sloan.cn
Title: {title}
ScriptType: v4.00+
WrapStyle: 2
Collisions: Normal
ScaledBorderAndShadow: yes
Aspect Ratio: {width}:{height}
YCbCr Matrix: TV.601
PlayResX: {width}
PlayResY: {height}

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
{style}

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
{dialogues}
"""

class SubtitlesASS:
    def __init__(self, data: dict, title: str):
        self.data = data
        self.title = title

    def generate(self):
        style_str, screen_width, screen_height = self._get_style_info()

        dialogues_list = self._convert_dialogues()
        
        return ass_base.format(
            title = self.title,
            style = style_str,
            dialogues = "\n".join(dialogues_list),
            width = screen_width,
            height = screen_height
        )
    
    def _get_style_info(self):
        style = config.get(config.subtitle_style)
        
        screen_width = style["resolution"]["width"]
        screen_height = style["resolution"]["height"]

        style_str = "Style: Default,{font},{size},{primary_color},{secondary_color},{border_color},{shadow_color}," \
                    "{bold},{italic},{underline},{strikeout},100,100,0,0,1,{border},{shadow},{alignment},{margin_l},{margin_r},{margin_v},1".format(
            font = style["font"]["name"],
            size = style["font"]["size"],
            primary_color = style["color"]["primary"],
            secondary_color = style["color"]["secondary"],
            border_color = style["color"]["border"],
            shadow_color = style["color"]["shadow"],
            bold = int(style["font"]["bold"]),
            italic = int(style["font"]["italic"]),
            underline = int(style["font"]["underline"]),
            strikeout = int(style["font"]["strike"]),
            border = style["border"]["border"],
            shadow = style["border"]["shadow"],
            alignment = style["alignment"],
            margin_l = style["margin"]["left"],
            margin_r = style["margin"]["right"],
            margin_v = style["margin"]["vertical"]
        )

        return style_str, screen_width, screen_height
    
    def _convert_dialogues(self):
        dialogues_list = []

        for item in self.data.get("body", []):
            start = Time.format_ass_time_by_seconds(item.get("from", 0))
            end = Time.format_ass_time_by_seconds(item.get("to", 0))
            content = item.get("content", "")

            dialogues_list.append(f"Dialogue: 0,{start},{end},Default,,0,0,0,,{content}")

        return dialogues_list
    