#!/usr/bin/env python3
# install python3-pydbus

import sys
import argparse

try:
    from pydbus import SessionBus
except ImportError as e:
    print("Cannot find pydbus module. Please install first")
    sys.exit(1)

def sgn(num):
    if num > 0:
        return "+" + str(num)
    else: 
        return str(num)

def seek(pos):
    iPos = int(pos[0])
    print("Pos: " + sgn(iPos) + "us = " + sgn(iPos / 1000000) + "s")
    gSayonaraInstance.Seek(iPos)


def setVolume(vol):
    fVol = float(vol[0])
    if fVol > 1.0: 
        fVol = fVol / 100.0

    print("Vol: " + fVol)
    gSayonaraInstance.SetVolume(fVol)

def setShuffle(enabled):
    bEnabled = int(enabled[0])
    gSayonaraInstance.SetShuffle(bEnabled)

def main():
    bus = SessionBus()
    try:
        global gSayonaraInstance
        gSayonaraInstance = bus.get(
            "org.mpris.MediaPlayer2.sayonara",  # Bus name
            "/org/mpris/MediaPlayer2"           # Object path
        )
    except:
        print("Sayonara not running")
        sys.exit(1)

    functionMap = {
        "play":       gSayonaraInstance.Play,
        "play-pause": gSayonaraInstance.PlayPause,
        "pause":      gSayonaraInstance.Pause,
        "stop":       gSayonaraInstance.Stop,
        "seek-us":    seek,
        "set-shuffle": setShuffle,
        "next":       gSayonaraInstance.Next,
        "previous":   gSayonaraInstance.Previous,
        "set-volume": setVolume,
        "inc-volume": gSayonaraInstance.IncreaseVolume,
        "dec-volume": gSayonaraInstance.DecreaseVolume,
        "raise":      gSayonaraInstance.Raise,
        "quit":       gSayonaraInstance.Quit
    }

    parser = argparse.ArgumentParser(description="Sayonara Control")
    parser.add_argument("command", help=str(list(functionMap.keys())))
    parser.add_argument("arguments", nargs="?")

    try:
        args = parser.parse_args()
    except:
        parser.print_help()
        exit(1)

    if not args.arguments:
        functionMap[args.command]()
    else:
        functionMap[args.command](args.arguments)

if __name__ == "__main__": main()
