#!/usr/bin/env python3

import i3ipc
import cgi
from k5dstatus.utils import get_config, make_block


config = get_config('focused-window')

truncate_length = config.get('truncate-length', 100)


def process_title(name):
    if not name:
        return ""

    if len(name) > truncate_length:
        name = name[0:truncate_length].rstrip() + '…'

    return cgi.escape(name)


def on_focus_title_change(i3, e):
    global block
    if e.container.focused:
        block.Update({'full_text': process_title(e.container.name)})

i3 = i3ipc.Connection()
i3.on('window::focus', on_focus_title_change)
i3.on('window::title', on_focus_title_change)


with make_block(
    name="focused-window",
    full_text=process_title(i3.get_tree().find_focused().name),
    markup="pango"
) as bgen:
    block = bgen()

    i3.main()
