from utils.common.formatter.formatter import FormatUtils

from utils.config import Config

class Json2ASS:
    @staticmethod
    def get_dialogue_list(json_data: dict):
        dialogue_list = []

        for entry in json_data["body"]:
            dialogue_list.append((
                FormatUtils.format_ass_timestamp(entry["from"]),
                FormatUtils.format_ass_timestamp(entry["to"]),
                entry["content"]
            ))

        return dialogue_list

class SubtitleASSFile:
    def __init__(self, json_data: dict, resolution: dict):
        self.json_data = json_data
        self.video_width = resolution.get("width")
        self.video_height = resolution.get("height")

    def get_contents(self):
        sections = (self.get_script_info_section(), self.get_styles_section(), self.get_events_section())

        return "\n\n".join(sections)
    
    def get_script_info_section(self):
        data = [
            (";", "Script generated by Bili23 Downloader"),
            (";", "https://bili23.scott-sloan.cn"),
            ("ScriptType", "v4.00+"),
            ("PlayResX", self.video_width),
            ("PlayResY", self.video_height),
            ("Aspect Ratio", f"{self.video_width}:{self.video_height}"),
            ("Collisions", "Normal"),
            ("WrapStyle", "2"),
            ("ScaledBorderAndShadow", "yes"),
        ]

        return self.format_section("Script Info", data)
    
    def get_styles_section(self):
        data = [
            ("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", self.get_subtitle_style())
        ]

        return self.format_section("V4+ Styles", data)
    
    def get_events_section(self):
        data = [
            ("Format", "Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"),
        ]
        
        converter = Json2ASS()

        dialogues = [
            ("Dialogue", f"2,{start_time},{end_time},Default,,0,0,0,,{content}")
            for (start_time, end_time, content) in converter.get_dialogue_list(self.json_data)
        ]

        data.extend(dialogues)

        return self.format_section("Events", data)
    
    def get_subtitle_style(self):
        subtitle_style = Config.Basic.ass_style.get("subtitle")

        style_data = {
            "Name": "Default",
            "Fontname": subtitle_style.get("font_name"),
            "Fontsize": subtitle_style.get("font_size"),
            "PrimaryColour": subtitle_style.get("primary_color"),
            "SecondaryColour": subtitle_style.get("secondary_color"),
            "OutlineColour": subtitle_style.get("border_color"),
            "BackColour": subtitle_style.get("shadow_color"),
            "Bold": subtitle_style.get("bold"),
            "Italic": subtitle_style.get("italic"),
            "Underline": subtitle_style.get("underline"),
            "StrikeOut": subtitle_style.get("strikeout"),
            "ScaleX": subtitle_style.get("scale_x"),
            "ScaleY": subtitle_style.get("scale_y"),
            "Spacing": subtitle_style.get("spacing"),
            "Angle": subtitle_style.get("angle"),
            "BorderStyle": 3 if subtitle_style.get("non_alpha") else 1,
            "Outline": subtitle_style.get("border"),
            "Shadow": subtitle_style.get("shadow"),
            "Alignment": subtitle_style.get("alignment"),
            "MarginL": subtitle_style.get("marginL"),
            "MarginR": subtitle_style.get("marginR"),
            "MarginV": subtitle_style.get("marginV"),
            "Encoding": 1
        }

        return ",".join([str(value) for value in style_data.values()])
    
    def format_section(self, title: str, data: list):
        return f"[{title}]\n" + "\n".join([f"{key}: {value}" if key != ";" else f"; {value}" for (key, value) in data])