import os
import subprocess
import socket
from libqtile import layout, bar, widget, hook
from libqtile.config import Group, Screen
from libqtile.dgroups import simple_key_binder
from libqtile.config import Key, KeyChord
from libqtile.command import lazy
from libqtile.config import Click, Drag
from colors import monokai,my_colors

hostname = socket.gethostname()
groups = []
group_names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ]
group_labels = ["Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ", ]
group_layouts = ["monadtall", "monadtall", "monadtall", "monadtall",
                 "monadtall", "monadtall", "monadtall", "monadtall",
                 "monadtall", "monadtall", ]

for i in range(len(group_names)):
    groups.append(
        Group(name=group_names[i],
              layout=group_layouts[i].lower(),
              label=group_labels[i],))


def init_layout_theme():
    """Layout default theme."""
    return {"margin": 5,
            "border_width": 2,
            "border_focus": monokai["yellow"],
            "border_normal": my_colors["black"],
            }

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

layout_theme = init_layout_theme()

layouts = [
    layout.MonadTall(**layout_theme),
    layout.Floating(**layout_theme),
    layout.Matrix(**layout_theme),
    layout.VerticalTile(**layout_theme),
]

@hook.subscribe.client_new
def float_my_app(window):
    if window.window.get_name() == "thanos/pass-launcher":
        window.floating = True

# Widgets
def init_widgets_defaults():
    """Set widget default settings."""
    return dict(font="JetBrains Mono",
                fontsize=14,
                padding=2,
                foreground=monokai["fg"],
                background=my_colors["black"],)


widget_defaults = init_widgets_defaults()

def init_widgets_list():
    """My widget list."""
    widgets_list = [
        widget.Spacer(length=7),
        widget.Image(
            filename="~/.config/qtile/larry2.png",
            scale="True",
            margin=2,),
        widget.Spacer(length=7,),
        widget.GroupBox(
            font="FontAwesome",
            fontsize=20,
            padding=3,
            margin=4,
            borderwidth=1,
            active=monokai["green"],
            inactive=monokai["grey"],
            rounded=False,
            highlight_method="line",
            this_current_screen_border=monokai["red"],
            other_current_screen_border=monokai["grey"],),
        widget.CurrentLayout(
            foreground=monokai["fg"],
            background=my_colors["black2"],),
        widget.Spacer(length=5),
        widget.WindowName(
            font="JetBrains Mono Bold",
            fontsize=12,
            foreground=monokai["green"],),
        widget.Spacer(length=10,),
        widget.KeyboardLayout(
            configured_keyboards = ['us','gr','bg phonetic'],
            fontsize=12,
            display_map={'us':'US', 'gr':'EL', 'bg phonetic':'BG'},
            padding=15,
            fmt="[{}]"
        ),
        widget.Image(
            filename="~/.config/qtile/volume1.png",
            scale=True,),
        widget.Spacer(length=7, padding=10,),
        widget.Volume(
            fontsize=15,
            get_volume_command="amixer get Master | awk '/Front Left:/ { print substr($5, 2, length($5)-2) }'",
            fmt='{} ',
            foreground=monokai['yellow'],
            margin=10,),
        widget.Spacer(length=7,padding=10,),
        widget.Image(
            filename="~/.config/qtile/pram2.png",
            scale=True,),
        widget.Memory(
            font="JetBrains Mono Bold",
            measure_mem="G",
            fontsize=15,
            foreground=monokai["dark-cyan"],),
        widget.MemoryGraph(
            type='box',
            graph_color=monokai["yellow"],
            foreground=monokai["fg"],),
        widget.Spacer(length=7),
        widget.Image(filename="~/.config/qtile/cpu1.png", scale=True,),
        widget.ThermalSensor(
            font="JetBrains Mono Bold",
            threshold=50,
            fontsize=15,
            foreground=monokai["dark-cyan"],),
        widget.CPUGraph(
            type='box',
            graph_color=monokai["yellow"],),
        widget.Spacer(length=5),
        widget.TextBox(
            font="FontAwesome",
            text="  ",
            foreground=monokai["orange"],
            padding=2,
            fontsize=18),
        widget.Clock(
            font='JetBrains Mono Bold',
            foreground=monokai["violet"],
            fontsize=16,
            format="%A %d/%m | %H:%M"),
        widget.Spacer(length=6),
        widget.Systray(
            icon_size=20,
            padding=10,
            margin=10,),
        widget.Spacer(length=5),
        ]
    return widgets_list

battery_widget = widget.Battery(format='{char} {percent:2.0%} {hour:d}:{min:02d} ', font='Jetbrains Mono')
widgets_list = init_widgets_list()

def init_widgets_screen1():
    """Init every widget for primary screen."""
    widgets_screen1 = init_widgets_list()
    if hostname == "hermes":
        widgets_screen1.append(battery_widget)
    return widgets_screen1

def init_widgets_screen2():
    """Remove systray and spacer for second screen."""
    widgets_screen2 = init_widgets_list()
    return widgets_screen2[:-2]

widgets_screen1 = init_widgets_screen1()
widgets_screen2 = init_widgets_screen2()


def init_screens():
    """Panel settings."""
    return [Screen(top=bar.Bar(widgets=init_widgets_screen1(), size=33,
                               margin=11),),
            Screen(top=bar.Bar(widgets=init_widgets_screen2(), size=28,
                               margin=7))]

screens = init_screens()
follow_mouse_focus = True
bring_front_click = False
cursor_warp = True
auto_fullscreen = True
focus_on_window_activation = "smart"  # or focus
wmname = "Qtile-Apo11o"

## Keys
# Use this to change between workspaces
dgroups_key_binder = simple_key_binder("mod4")
mod = "mod4"
browser = "firefox"

keys = [
    Key([mod],"r",lazy.spawn("rofi -show drun -modi drun -show-icons"),),
    Key([mod, "shift"], "l", lazy.spawn("slock")),
    Key([mod],"q",lazy.window.kill()),
    Key([mod,"shift"],"r",lazy.restart()),
    # Switch focus of monitors
    Key([mod],"period",lazy.next_screen()),
    # Treetab controls
    Key([mod,"shift"],"b",lazy.layout.move_left()),
    Key([mod,"shift"],"f",lazy.layout.move_right()),
    # Emacs
    Key([mod], "Return", lazy.spawn("emacsclient -c")),
    Key([mod], "w", lazy.spawn("emacsclient -e '(thanos/pass-launcher)'")),
    # Layout control
    KeyChord([mod], "l", [
        Key([], "n", lazy.next_layout()),
        Key([], "g", lazy.layout.grow(),lazy.layout.increase_nmaster()),
        Key([],"s",lazy.layout.shrink(),lazy.layout.decrease_nmaster()),
    ]),
    # Window controls
    Key([mod],"n",lazy.layout.down(),),
    Key([mod],"p",lazy.layout.up(),),
    Key([mod,"shift"],"n",lazy.layout.shuffle_down(),lazy.layout.section_down(),),
    Key([mod,"shift"],"p",lazy.layout.shuffle_up(),lazy.layout.section_up(),),
    Key([mod],"o",lazy.layout.normalize(),),
    Key([mod],"m",lazy.layout.maximize(),),
    Key([mod,"shift"],"f",lazy.window.toggle_floating(),),
    Key([mod],"f",lazy.window.toggle_fullscreen(),),
    # Stack controls
    Key([mod,"shift"],"Tab",lazy.layout.rotate(),lazy.layout.flip(),),
    Key([mod,"shift"],"space", lazy.layout.toggle_split(),),
    # Volume controls
    Key([],"XF86AudioLowerVolume",lazy.spawn("amixer sset Master 5%-")),
    Key([],"XF86AudioRaiseVolume",lazy.spawn("amixer sset Master 5%+")),
    # Keyboard
    Key([mod], "space", lazy.widget["keyboardlayout"].next_keyboard(), desc="Next keyboard layout."),
    Key([],"F9", lazy.spawn("setxkbmap gr -option ctrl:swapcas")),
    Key([],"F10", lazy.spawn("setxkbmap us -option ctrl:swapcaps")),
    # Thinkpad
    Key([],"F1", lazy.spawn("brightnessctl --device='intel_backlight' set 5%-")),
    Key([],"F2", lazy.spawn("brightnessctl --device='intel_backlight' set +5%")),
    Key([],"F4", (lazy.spawn("/home/thanos/.scripts/keyboard-light-x220.sh"))),
    Key([mod, "control"], "q", lazy.shutdown()),
    ]

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()),
 ]