import os
import subprocess
from libqtile import bar, extension, hook, layout, widget
from libqtile.lazy import lazy
from libqtile.config import Click, Drag, DropDown, Group, Key, Match, ScratchPad, Screen

@hook.subscribe.startup_once
def autostart():
    home = os.path.expanduser('~/.config/qtile/autostart.sh')
    subprocess.Popen([home])

mod = "mod4"
groups = [
    Group("1", label="\uf292"),
    Group("2", label="\uf738", matches=[Match(wm_class=["firefox"])]),
    Group("3", label="\uf70d", matches=[Match(wm_class=["Ferdium", "discord", "Signal"])]),
    Group("4", label="\uf7aa", matches=[Match(wm_class=["mutt"])]),
    Group("5", label="\uf120"),
    Group("6", label="\uf120"),
    Group("7", label="\uf09c", matches=[Match(wm_class=["1Password"])]),
    Group("8", label="\uf198", matches=[Match(wm_class=["Slack"])]),
    Group("9", label="\uf296"),
    Group("0", label="\uf2bb", matches=[Match(wm_class=["workfx"])]),
]

keys = [
    # switch between windows
    Key([mod], "h", lazy.layout.left()),
    Key([mod], "l", lazy.layout.right()),
    Key([mod], "j", lazy.layout.down()),
    Key([mod], "k", lazy.layout.up()),
    Key([mod], "Left", lazy.layout.left()),
    Key([mod], "Right", lazy.layout.right()),
    Key([mod], "Down", lazy.layout.down()),
    Key([mod], "Up", lazy.layout.up()),
    # move windows
    Key([mod, "control"], "h", lazy.layout.shuffle_left()),
    Key([mod, "control"], "l", lazy.layout.shuffle_right()),
    Key([mod, "control"], "j", lazy.layout.shuffle_down()),
    Key([mod, "control"], "k", lazy.layout.shuffle_up()),
    # resize windows
    Key([mod, "shift"], "h", lazy.layout.grow_left()),
    Key([mod, "shift"], "l", lazy.layout.grow_right()),
    Key([mod, "shift"], "j", lazy.layout.grow_down()),
    Key([mod, "shift"], "k", lazy.layout.grow_up()),
    Key([mod, "shift", "control"], "0", lazy.layout.normalize()),
    # app binds
    Key([mod], "Return",          lazy.spawn("sh -c 'BROWSER=firefox st'")),
    Key([mod], "space",           lazy.spawncmd()),
    Key([mod], "a",               lazy.spawn("authenticator")),
    Key([mod], "e",               lazy.spawn("selector-chars")),
    Key([mod], "i",               lazy.spawn("scrot -f -s 'scrot_%Y-%m-%d_%H-%M-%S_%s.png'")),
    Key([mod], "m",               lazy.spawn("sh -c 'pgrep -x neomutt > /dev/null || BROWSER=firefoxn st -n mutt -e neomutt'")),
    Key([mod, "shift"], "i",      lazy.spawn("scrot -f 'scrot_%Y-%m-%d_%H-%M-%S_%s.png'")),
    Key([mod, "shift"], "Return", lazy.spawn("sh -c 'terminal_profile=work BROWSER=workfx st'")),
    Key([mod, "control"], "a",    lazy.spawn("selector-audio")),
    Key([mod, "control"], "b",    lazy.spawn("selector-bluetooth")),
    # WM control
    Key([mod], "f", lazy.window.toggle_floating()),
    Key([mod], "q", lazy.window.kill()),
    Key([mod, "control", "shift"], "l", lazy.spawn("physlock")),
    Key([mod, "control", "shift"], "q", lazy.shutdown()),
    Key([mod, "control", "shift"], "r", lazy.reload_config()),
    Key([mod], "r", lazy.reload_config()),
    # media keys
    Key([], "XF86AudioMute",         lazy.spawn("pactl set-sink-mute @DEFAULT_SINK@ toggle")),
    Key([], "XF86AudioMicMute",      lazy.spawn("sb-volume key")),
    Key([], "XF86AudioRaiseVolume",  lazy.spawn("sb-volume inc")),
    Key([], "XF86AudioLowerVolume",  lazy.spawn("sb-volume dec")),
    Key([], "XF86MonBrightnessUp",   lazy.spawn("xbacklight -inc 10")),
    Key([], "XF86MonBrightnessDown", lazy.spawn("xbacklight -dec 10")),
]

for i in groups[:10]:
    keys.extend(
        [
            # mod1 + letter of group = switch to group
            Key(
                [mod], i.name, lazy.group[i.name].toscreen(),
                desc="Switch to group {}".format(i.name),
            ),
            # Key( [mod, "shift"], i.name, lazy.window.togroup(i.name, switch_group=True),
            #     desc="Switch to & move focused window to group {}".format(i.name),
            # ),
            Key([mod, "shift"], i.name, lazy.window.togroup(i.name),
                desc="move focused window to group {}".format(i.name)
            ),
        ]
    )

layouts = [
    layout.Columns(
        border_focus='#0094d8',
        border_normal="#272822",
        border_on_single = False,
        border_width=5,
        insert_position=1,
        margin=[5, 5, 5, 5]
    ),
]

widget_defaults = dict(
    background='#272822',
    font="RobotoMono Nerd Font Medium",
    fontsize=14,
    foreground='#feffff',
)
extension_defaults = widget_defaults.copy()

def yubikey_replace(text):
    return text.replace('YubiKey is waiting for a touch', 'Touch the Yubikey')

screens = [
    Screen(
        top=bar.Bar(
            [
                widget.GroupBox(
                    active='#feffff',
                    disable_drag=True,
                    fontsize=18,
                    highlight_method='block',
                    rounded=False,
                    this_current_screen_border='#005577',
                    urgent_alert_method='block',
                    urgent_border='#770000',
                ),
                widget.Prompt(
                    bell_style=None,
                    prompt='open: ',
                    record_history=False,
                ),
                widget.Spacer(),
                widget.Notify(
                    background='#e8b923',
                    background_low='#272822',
                    background_urgent='#770000',
                    foreground='#000000',
                    foreground_low='#c7c7c7',
                    foreground_urgent='#feffff',
                    font='RobotoMono Nerd Font Bold',
                    parse_text=yubikey_replace,
                ),
                widget.GenPollCommand(
                    background='#005577',
                    foreground='#feffff',
                    update_interval=1,
                    cmd="sb-mail",
                ),
                widget.GenPollCommand(
                    background='#770000',
                    foreground='#feffff',
                    update_interval=1,
                    cmd="sb-volume",
                ),
                widget.GenPollCommand(
                    background='#770000',
                    foreground='#feffff',
                    update_interval=1,
                    cmd="sb-network",
                ),
                widget.GenPollCommand(
                    update_interval=1,
                    cmd="sb-battery",
                ),
                widget.Clock(
                    format='[%d] %H:%M:%S',
                ),
                widget.Systray(),
            ],
            24,
            margin=[5, 5, 0, 5]
        ),
        wallpaper=os.environ['XDG_CONFIG_HOME'] + '/qtile/wallpaper.img',
        wallpaper_mode='fill',
    ),
]

mouse = [
    Drag([mod], "Button1", lazy.window.set_position_floating(), start=lazy.window.get_position()),
    Drag([mod], "Button3", lazy.window.set_size_floating(), start=lazy.window.get_size()),
    Click([mod], "Button2", lazy.window.bring_to_front()),
]

floating_layout = layout.Floating(
    float_rules=[
        *layout.Floating.default_float_rules,
        Match(wm_class='authenticator'),
    ],
    border_focus='#005577',
    border_normal="#272822",
    border_width=5,
)
