#!/usr/bin/env python

"""The main ardj CLI entry point."""

__author__ = "Justin Forest <hex@umonkey.net>"


import os
import sys

_root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if os.path.exists(os.path.join(_root, "src/ardj")):
    _path = os.path.join(_root, "src")
    sys.path.insert(0, _path)
    os.environ["ardj_python_path"] = _path

import logging
logging.getLogger().setLevel(logging.DEBUG)

from ardj.cli import *


def cmd_config():
    """
    Edit config file

    Creates default files when necessary.
    """
    from ardj.monitor import autocreate_configs
    configs = autocreate_configs()

    from ardj.util import edit_file
    edit_file(configs["ardj.yaml"])


def cmd_console(*args):
    """Open command console"""
    from ardj import console
    return console.run_cli(args)


def cmd_db(*args):
    """Database related commands"""
    import ardj.database
    return cli_main(ardj.database, "ardj db", *args)


def cmd_jabber(*args, **kwargs):
    """Jabber commands"""
    import ardj.jabber
    return cli_main(ardj.jabber, "ardj jabber", *args, **kwargs)


def cmd_listeners(*args):
    """Get listeners counts."""
    from ardj import listeners
    cli_main(listeners, "ardj listeners", *args)


def cmd_old(*args):
    """Access old CLI commands"""
    from ardj import cli_old
    cli_main(cli_old, "ardj old", *args)


def cmd_reload(*args):
    """Reload playlists (only for ices)"""
    from signal import SIGHUP
    from ardj.util import signal_by_pid_file
    signal_by_pid_file("ices.pid", SIGHUP)


def cmd_replaygain(*args):
    """Calculate ReplayGain"""
    from ardj import replaygain
    cli_main(replaygain, "ardj replaygain", *args)


def cmd_run(*args):
    """Start broadcasting"""
    from ardj import monitor
    monitor.cmd_run(*args)


def cmd_scrobbler(*args):
    """Last.fm interaction"""
    from ardj import scrobbler
    cli_main(scrobbler, "ardj scrobbler", *args)


def cmd_server(*args, **kwargs):
    """Run the whole server"""
    from ardj import monitor
    cli_main(monitor, "ardj server", *args)


def cmd_skip(*args):
    """Skip to next track."""
    from ardj.console import on_skip
    print on_skip([], "console")


def cmd_tracks(*args):
    """Work with tracks"""
    from ardj import tracks
    cli_main(tracks, "ardj tracks", *args)


def cmd_web(*args):
    """Built-in web server"""
    from ardj import server
    cli_main(server, "ardj server", *args)


if __name__ == "__main__":
    cli_main(globals(), *sys.argv)
