# theory MPD client
# Copyright (C) 2008  Ryan Roemmich <ralfonso@gmail.com>
#
# 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 logging
import mpd

from pylons import request, response, session
from pylons import tmpl_context as c
from pylons import app_globals as g
from pylons.controllers.util import abort
from pylons.decorators import jsonify

from mpd import CommandError

from theory.lib.base import BaseController, render

log = logging.getLogger(__name__)

class MpdcontrolController(BaseController):
    requires_auth = True

    @jsonify
    def status(self):
        """ 
        this is the status data that the main indexes calls on an interval.
        uses the pylons @jsonify decorator to turn the output into something
        that can be parsed by JQuery's getJSON() function
        """
            
        self.m = g.p.connect()
        current = self.m.currentsong()
        status = self.m.status()
        #m.close()

        return dict(track=current,status=status)

    @jsonify
    def fs_status(self):
        """ 
        similar to status() but includes a forward-looking playlist 
        for the fullscreen widget
        """

        try:
            self.m = g.p.connect()
        except ConnectionClosed:
            return render('/null.html')

        status = self.m.status()
        current = self.m.currentsong()
        playlist = self.m.playlistinfo()

        track = 0
        found_current = False
        remaining_playlist = []

        for pl in playlist:
            if found_current:
                remaining_playlist.append(pl)

            if 'id' in current:
                if pl['id'] == current['id']:
                    found_current = True
           
            track += 1

        #m.close()
        return dict(status=status,current=current,playlist=remaining_playlist)

    def setvolume(self,id):
        self.m = g.p.connect()

        try: