#!/usr/bin/env python3

import subprocess
import time

MPC_CLIENT = "mpc"
WINDOW_LENGTH = 40
SEPARATOR = " :: "
ERROR_OUTPUT = "--"

def get_status_information() -> str:
    process = subprocess.run([MPC_CLIENT], stdout=subprocess.PIPE)
    output_lines = process.stdout.decode().strip().split("\n")
    return output_lines[1] if process.returncode == 0 and len(output_lines) > 1 else ERROR_OUTPUT

def get_playback_information() -> str:
    status_fields = get_status_information().split(" ");
    return status_fields[0] if len(status_fields) > 0 else ""

def get_playback_code() -> str:
    playback_status = get_playback_information();
    if playback_status == "[playing]":
        return ""
    elif playback_status == "[paused]":
        return "‖"
    else:
        return "■"

    status_fields = get_status_information().split(" ");
    return status_fields[0] if len(status_fields) > 0 else ""

def get_song_information() -> str:
    process = subprocess.run([MPC_CLIENT, "-f", "[%title% ][@%name%]", "current"], stdout=subprocess.PIPE)
    song_info = process.stdout.decode().strip() if process.returncode == 0 else ""

    if len(song_info) > WINDOW_LENGTH:
        offset = int((int(time.time()) % 60) / 60 * len(song_info))
        remainingLength = len(song_info) - offset
        if remainingLength >= WINDOW_LENGTH:
            return song_info[offset:offset + WINDOW_LENGTH]
        else:
            return song_info[offset:offset + remainingLength] + SEPARATOR + song_info[0:WINDOW_LENGTH - remainingLength]
    else:
        return song_info

print((get_playback_code() + " " + get_song_information()).strip())
