import os
import subprocess
from swayipc import Swayipc
from warehouse import get_base

Logs = "/tmp/sway_boot.log"


def apply_safe_config(sway):
    try:
        sway.cmd("default_border none")
        sway.cmd("default_floating_border none")
        sway.cmd("floating_modifier Mod4")
        sway.cmd("bindsym Mod4+Shift+grave reload")
        sway.cmd("bindsym Mod4+Shift+escape exit")
        sway.cmd("bindsym Mod4+q exec kitty")
        sway.cmd("bindsym Mod4+c kill")
        sway.cmd("exec notify-send 'Sway FUCKED!' 'Fallback active'")
        sway.cmd('for_window [app_id="xpad"] floating enable')
    except Exception:
        print("truely fucked")
        pass


def boot(base):
    base = os.path.expanduser(base)
    with open(Logs, "w") as f:
        return subprocess.run(
            ["python3", os.path.join(base, "main/swayconfig.py")],
            stdout=f,
            stderr=f
        ).returncode


def main():
    sway = Swayipc()
    base = get_base()
    if not base:
        print("BASE_SWAY isnt defined correctly. This WILL cause problems with startup.")
        return
    rc = boot(base)

    if rc != 0:
        apply_safe_config(sway)
        subprocess.Popen(["xpad", "-f", Logs])


if __name__ == "__main__":
    main()