#! /usr/bin/python3
# coding: utf-8

# Asynchronous Music Player Daemon client library for Python

# Copyright (C) 2015 Itaï BEN YAACOV

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import pprint
import sys
import ampd
import asyncio
import logging
import signal
import readline
import os


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


class AMPC(object):
    PROMPT = 'ampd: '

    def __init__(self):
        self.loop = asyncio.get_event_loop()
        self.client = ampd.Client()
        self.ampd = self.client.executor

        def interrupt(*args):
            print("^C")
            raise KeyboardInterrupt
        signal.signal(signal.SIGINT, interrupt)
        self.loop.run_until_complete(self.prompt())
        self.loop.close()

    @ampd.task
    async def prompt(self):
        await self.client.connect_to_server()
        while True:
            try:
                command = input(self.PROMPT)
            except (KeyboardInterrupt, EOFError):
                command = None
            if not command:
                print("Quitting")
                break
            try:
                command = eval(command, {name: getattr(self.ampd, name) for name in list(ampd.request.COMMANDS) + ['command_list', '_raw']})
            except Exception:
                sys.excepthook(*sys.exc_info())
                continue
            try:
                reply = await command
                MyPrettyPrinter().pprint(reply)
            except Exception as e:
                print('ERROR:', e)
        await self.client.close()


class MyPrettyPrinter(pprint.PrettyPrinter):
    def format(self, obj, context, maxlevels, level):
        if isinstance(obj, str):
            return (obj, True, False)
        return pprint.PrettyPrinter.format(self, obj, context, maxlevels, level)


try:
    readline.read_history_file(os.path.expanduser('~/.ampc_history'))
except FileNotFoundError:
    pass

app = AMPC()
readline.write_history_file(os.path.expanduser('~/.ampc_history'))
