#!/usr/bin/env python3

import subprocess
import time

connect_command = "default_monitor"

def get(cmd):
    return subprocess.check_output(cmd).decode("utf-8")

# - to count the occurrenc of " connected "
def count_screens(xr):
    return xr.count(" connected ")

# - to run the connect / disconnect command(s)
def run_command(cmd):
    subprocess.Popen([cmd])

# first count
xr1 = None

while True:
    # second count
    xr2 = count_screens(get(["xrandr"]))
    # check if there is a change in the screen state
    if xr2 != xr1:
        print("change")
        if xr2 == 2:

            # command to run if connected (two screens)
            run_command(connect_command)

    # set the second count as initial state for the next loop
    xr1 = xr2
    time.sleep(5)
