#!/usr/bin/env python3

import i3ipc
import dbus
import json
import cgi

i3dstatus = dbus.Interface(dbus.SessionBus().get_object(
                          'com.dubstepdish.i3dstatus',
                          '/com/dubstepdish/i3dstatus'),
                          'com.dubstepdish.i3dstatus')

config = json.loads(i3dstatus.get_config('focused-window'))

truncate_length = 100

if 'truncate-length' in config:
    truncate_length = config['truncate-length']


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):
    if e.container.focused:
        full_text = process_title(e.container.name)
        i3dstatus.show_block({
            "name": "focused-window",
            "full_text": full_text,
            "markup": "pango"
            })

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

i3dstatus.show_block({
            "name": "focused-window",
            "full_text": process_title(i3.get_tree().find_focused().name),
            "markup": "pango"
            })

i3.main()
