"""barmanager
helper script for eww bar from Shobu Ser'Hao

Usage:
    barmanager player get [-f --follow]

Options:
    -h --help       Show Help screen
    -f --follow     Loop on the output
"""
from docopt import docopt
from subprocess import run, Popen, PIPE
import json
import sys

def main():
    arguments = docopt(__doc__)
    if arguments["player"]:
        run(["echo", json.dumps(handle_player(arguments))])

def handle_player(arguments):
    if arguments["get"]:

        raw_metadata = run(["playerctl", "metadata"], capture_output=True).stdout.decode()
        metadata = parse_player_metadata(raw_metadata)
        if not arguments["--follow"]:
            return metadata

        if arguments["--follow"]:
            process = Popen(["playerctl", "metadata", "--follow"], stdout=PIPE)
            chars = b''
            row_count = 0
            for char in iter(lambda: process.stdout.read(1), b""):
                if char:
                    chars += char
                    if char == b"\n":
                        row_count += 1
                if row_count == len(metadata):
                    run(["echo", json.dumps(parse_player_metadata(chars.decode()))])
                    string = ''
                    row_count = 0

def parse_player_metadata(raw_string):
    metadata = {}
    for i in raw_string.strip().split("\n"):
        head = ''
        tail = ''
        spaces = 0
        for j in i:
            if spaces < 2:
                if j == " ":
                    spaces += 1
                else:
                    spaces = 0
                head += j
            else:
                tail += j
        metadata[head.strip().split(":")[-1]] = tail.strip()
    return metadata



if __name__ == "__main__":
    main()
    
