#!/usr/bin/env python3
"""Rewrite premium dialog action buttons: unified dark style, focused = white area.

All buttons share the same background/outline in the idle state (dark translucent
pill/circle with a subtle outline and light icon/text) and turn into a white area
with dark icon/text only while focused. Run once after geometry/design changes.
"""
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
ADDON = os.path.abspath(os.path.join(HERE, '..', '..'))
PREMIUM_DIR = os.path.join(ADDON, 'resources', 'skins', 'Default', '1080i', 'notifications', 'premium')
MEDIA = 'special://home/addons/plugin.video.milionar/resources/media/'

WHITE = 'FFECECF1'
BLACK = 'FF101014'
IDLE_FILL = '0FFFFFFF'
IDLE_STROKE = '38FFFFFF'
FOCUS_FILL = 'FFFFFFFF'


def image(left, top, width, height, texture, color, visible):
    return f"""            <control type="image">
                <left>{left}</left>
                <top>{top}</top>
                <width>{width}</width>
                <height>{height}</height>
                <texture colordiffuse="{color}">{MEDIA}{texture}</texture>
                <visible>{visible}</visible>
            </control>"""


def stroke(left, top, width, height, visible, texture='notif_pill_stroke.png', border=34):
    return f"""            <control type="image">
                <left>{left}</left>
                <top>{top}</top>
                <width>{width}</width>
                <height>{height}</height>
                <texture border="{border}" colordiffuse="{IDLE_STROKE}">{MEDIA}{texture}</texture>
                <visible>{visible}</visible>
            </control>"""


def pill_button(control_id, left, top, width, height, texture='notif_pill_fill.png', border=34,
                nav=None, label='', font='font12', align='center'):
    nav = nav or {}
    nav_lines = '\n'.join(f'                <{key}>{value}</{key}>' for key, value in nav.items())
    return f"""            <control type="button" id="{control_id}">
                <left>{left}</left>
                <top>{top}</top>
                <width>{width}</width>
                <height>{height}</height>
                <font>{font}</font>
                <textcolor>{WHITE}</textcolor>
                <focusedcolor>{BLACK}</focusedcolor>
                <label>{label}</label>
                <align>{align}</align>
                <aligny>center</aligny>
                <texturefocus border="{border}" colordiffuse="{FOCUS_FILL}">{MEDIA}{texture}</texturefocus>
                <texturenofocus border="{border}" colordiffuse="{IDLE_FILL}">{MEDIA}{texture}</texturenofocus>
{nav_lines}
            </control>"""


def circle_button(control_id, left, top, size, nav=None):
    nav = nav or {}
    nav_lines = '\n'.join(f'                <{key}>{value}</{key}>' for key, value in nav.items())
    return f"""            <control type="button" id="{control_id}">
                <left>{left}</left>
                <top>{top}</top>
                <width>{size}</width>
                <height>{size}</height>
                <font>font12</font>
                <textcolor>00FFFFFF</textcolor>
                <focusedcolor>00FFFFFF</focusedcolor>
                <label></label>
                <texturefocus colordiffuse="{FOCUS_FILL}">{MEDIA}notif_circle_fill.png</texturefocus>
                <texturenofocus colordiffuse="{IDLE_FILL}">{MEDIA}notif_circle_fill.png</texturenofocus>
{nav_lines}
            </control>"""


def label(left, top, width, height, font, color, visible, addon_id=None):
    text = f'$ADDON[plugin.video.milionar {addon_id}]' if addon_id else ''
    return f"""            <control type="label">
                <left>{left}</left>
                <top>{top}</top>
                <width>{width}</width>
                <height>{height}</height>
                <font>{font}</font>
                <textcolor>{color}</textcolor>
                <label>{text}</label>
                <align>left</align>
                <aligny>center</aligny>
                <visible>{visible}</visible>
            </control>"""


def info_button():
    return '\n'.join([
        '            <!-- Info -->',
        pill_button(110, 23, 200, 196, 70,
                    nav={'onleft': 'noop', 'onright': '111', 'onup': 'noop', 'ondown': '501'}),
        stroke(23, 200, 196, 70, '!Control.HasFocus(110)'),
        image(77, 220, 30, 30, 'notif_icon_info.png', WHITE, '!Control.HasFocus(110)'),
        image(77, 220, 30, 30, 'notif_icon_info.png', BLACK, 'Control.HasFocus(110)'),
        label(126, 219, 90, 33, 'font12', WHITE, '!Control.HasFocus(110)', 32142),
        label(126, 219, 90, 33, 'font12', BLACK, 'Control.HasFocus(110)', 32142),
    ])


def play_button(control_id, label_id, nav):
    return '\n'.join([
        '            <!-- Přehrát -->',
        pill_button(control_id, 233, 200, 267, 70, nav=nav),
        stroke(233, 200, 267, 70, f'!Control.HasFocus({control_id})'),
        image(287, 224, 28, 24, 'notif_icon_play.png', WHITE, f'!Control.HasFocus({control_id})'),
        image(287, 224, 28, 24, 'notif_icon_play.png', BLACK, f'Control.HasFocus({control_id})'),
        label(337, 219, 142, 33, 'font25_title', WHITE, f'!Control.HasFocus({control_id})', label_id),
        label(337, 219, 142, 33, 'font25_title', BLACK, f'Control.HasFocus({control_id})', label_id),
    ])


def close_button(control_id, nav):
    return '\n'.join([
        '            <!-- Zavřít -->',
        circle_button(control_id, 526, 201, 69, nav=nav),
        stroke(526, 201, 69, 69, f'!Control.HasFocus({control_id})', texture='notif_circle_stroke.png', border=None),
        image(550, 226, 20, 20, 'notif_icon_close.png', WHITE, f'!Control.HasFocus({control_id})'),
        image(550, 226, 20, 20, 'notif_icon_close.png', BLACK, f'Control.HasFocus({control_id})'),
    ])


def action_block(kind):
    if kind == 'info':
        return '\n\n'.join([
            '            <!-- Akční tlačítka -->',
            info_button(),
            play_button(111, 32139, {'onleft': '110', 'onright': '112', 'onup': 'noop', 'ondown': '501'}),
            close_button(112, {'onleft': '111', 'onright': 'noop', 'onup': 'noop', 'ondown': '503'}),
        ])
    if kind == 'countdown':
        stop = '\n'.join([
            '            <!-- Ukončit -->',
            pill_button(121, 23, 200, 196, 70, label='$ADDON[plugin.video.milionar 32141]',
                        font='font12', nav={'onleft': 'noop', 'onright': '120', 'onup': 'noop', 'ondown': 'noop'}),
            stroke(23, 200, 196, 70, '!Control.HasFocus(121)'),
        ])
        return '\n\n'.join([
            stop,
            play_button(120, 40004, {'onleft': '121', 'onright': '122', 'onup': 'noop', 'ondown': 'noop'}),
            close_button(122, {'onleft': '120', 'onright': 'noop', 'onup': 'noop', 'ondown': 'noop'}),
        ])
    raise ValueError(kind)


def fix_circle_stroke(block):
    # circles use a full-size stroke texture (no 9-slice border attribute)
    return block.replace(' border="None"', '')


def patch_file(path, start_marker, end_marker, kind):
    with open(path, encoding='utf-8') as fh:
        text = fh.read()
    start = text.index(start_marker)
    end = text.index(end_marker)
    new_block = fix_circle_stroke(action_block(kind)) + '\n\n'
    text = text[:start] + new_block + text[end:]
    with open(path, 'w', encoding='utf-8') as fh:
        fh.write(text)
    print(f"patched {os.path.basename(path)}")


def main():
    episode = os.path.join(PREMIUM_DIR, 'DialogEpisodeInfoWithGame.xml')
    movie = os.path.join(PREMIUM_DIR, 'DialogMovieInfoWithGame.xml')
    countdown = os.path.join(PREMIUM_DIR, 'DialogAutoplayCountdown.xml')

    patch_file(episode, '            <!-- Akční tlačítka -->', '            <!-- Plot panel -->', 'info')
    patch_file(movie, '            <!-- Akční tlačítka -->', '            <!-- Plot panel -->', 'info')
    patch_file(countdown, '            <!-- Ukončit', '            <!-- Progress odpočtu -->', 'countdown')

    with open(countdown, encoding='utf-8') as fh:
        text = fh.read()
    text = text.replace('<defaultcontrol always="true">122</defaultcontrol>', '<defaultcontrol always="true">120</defaultcontrol>')
    with open(countdown, 'w', encoding='utf-8') as fh:
        fh.write(text)
    print("countdown default focus -> 120 (Přehrát)")
    return 0


if __name__ == '__main__':
    sys.exit(main())
