#!env python3

import os
import json
import subprocess
from xdg import BaseDirectory

def shell(cmd):
    return subprocess.run(cmd, shell=True, stdout=subprocess.PIPE).stdout.decode("utf-8")

class State:
    def __init__(self):
        cmd = "xrandr | grep \" connected\" | sed -e \"s/\\([A-Z0-9]\\+\\) connected.*/\\1/\" | sed 's/ *$//'"
        self.connected = set(shell(cmd).strip().split("\n"))

        cmd = "xrandr | grep -e \" connected [^(]\" | sed -e \"s/\\([A-Z0-9]\\+\\) connected.*/\\1/\""
        self.active = set(shell(cmd).strip().split("\n"))

class Configuration:
    def __init__(self, name, **params):
        self.name = name
        self.outputs = set(params['outputs'])
        if 'transition_output' in params:
            self.transition_output = params['transition_output']
        else:
            self.transition_output = None
        self.command = params['command']

class Config:
    def __init__(self, **params):
        self.configurations = [Configuration(name, **c) for name, c in params['configurations'].items()]
        if 'post_commands' in params:
            self.post_commands = params['post_commands']
        else:
            self.post_commands = []

config_file = BaseDirectory.save_config_path("") + "fix_display.json"
config = None
with open(config_file, "r") as f:
    config = Config(**(json.load(f)))

state = State()

print("Connected outputs: {}".format(state.connected))
print("Active outputs: {}".format(state.active))

for c in config.configurations:
    if c.outputs == state.connected:
        print("Selected: {}".format(c.name))

        if c.transition_output:
            cmd = "xrandr --output {} --auto".format(c.transition_output)
            for o in state.active:
                if not o == c.transition_output:
                    cmd += " --output {} --off".format(o)
            print("Transition output:\n  {}".format(cmd))
            shell(cmd)

        cmd = c.command
        print("Configure outputs:\n  {}".format(cmd))
        shell(cmd)

if len(config.post_commands) > 0:
    print("Post commands:")
    for cmd in config.post_commands:
        print("  {}".format(cmd))
        shell(cmd)
