#!/usr/bin/python3 -u
from subprocess import run, Popen
import json
import os
import argparse


def parse_args() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser()
    parser.add_argument('plug', help='Plug ID for monitor')
    return parser.parse_args()


def get_index(name, swaymsg):
    for num, output in enumerate(swaymsg):
        if output['name'] == name:
            return num
    return None


def main():
    run(['pkill', '-x', 'sunshine'], check=False)

    args = parse_args()

    swaymsg = json.loads(run(
        ['swaymsg', '-t', 'get_outputs'], capture_output=True, check=True
    ).stdout.decode('utf-8'))
    index = get_index(args.plug, swaymsg)

    # print(index)
    configfile = os.path.expanduser('~/.config/sunshine/sunshine.conf')
    with open(configfile, 'r') as file:
        data = file.readlines()

    with open(configfile, 'w') as file:
        for num, line in enumerate(data):
            if 'output_name' in line:
                data[num] = f'output_name = {index}'
        file.write('\n'.join(data))

    logfile = os.path.expanduser('~/.cache/sunshine.log')
    with open(logfile, 'w') as file:
        Popen(['sunshine'], stdout=file, stderr=file)


if __name__ == "__main__":
    main()
