"""
Pympc is a client for Music Player Daemon.
Copyright (C) 2004  Magnus Bjernstad <bjernstad@gmail.com>

This file is part of Pympc.

Pympc 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 2 of the License, or
(at your option) any later version.

Pympc 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 Pympc; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""
import gtk, pympc, os, gobject

class Cover:
    mode = 'fit'
    covers = {'front': [], 'back': [], 'other': []}

    def __init__(self, gui_file, music_dir):
        self.gui_popup = gtk.glade.XML(gui_file, 'cover_popup')
        self.gui_popup.signal_autoconnect(self)

        self.gui_main = gtk.glade.XML(gui_file, 'cover_root')
        self.gui_main.signal_autoconnect(self)
        self.w = self.gui_main.get_widget
        self.contents = self.w('cover_root')

        self.music_dir = music_dir
        image = gtk.Image()
        self.pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, 1, 1)
        self.pixbuf_ar = 1.0
        image.set_from_pixbuf(self.pixbuf)

    def __set_type(self, type, filename=''):
        if type in ('front', 'back'):
            active_cover = self.covers[type][0]
        if type == 'other':
            active_cover = filename
        self.load_file(active_cover)

    def new_song(self, path):
        self.__find_covers(path)
        
        if len(self.covers['front']) > 0:
            active_cover = self.covers['front'][0]
        else:
            if len(self.covers['other']) > 0:
                active_cover = self.covers['other'][0]
            else:
                active_cover = None
        self.load_file(active_cover)

    def __find_covers(self, path):
        dir = os.path.dirname(os.path.join(self.music_dir, path))
        try:
            files = os.listdir(dir)
        except OSError:
            return
        images = filter(lambda x: os.path.splitext(x.lower())[1] in ('.jpg', '.jpeg', '.png', '.tiff', '.gif'), files)
        covers = {'front': [], 'back': [], 'other': []}
        for image in images:
            if image.lower().find('front')  != -1 and len(covers['front']) == 0:
                covers['front'].append(os.path.join(dir,image))
            elif image.lower().find('back')  != -1 and len(covers['back']) == 0:
                covers['back'].append(os.path.join(dir, image))
            else:
                covers['other'].append(os.path.join(dir, image))
        covers['other'].sort()
        self.covers = covers

    def on_mouse_motion(self, widget, event):
        if not event.state & gtk.gdk.BUTTON1_MASK:
            return True
        hadj = widget.get_hadjustment()
        vadj = widget.get_vadjustment()
        dx = event.x_root - self.prev_x
        dy = event.y_root - self.prev_y
        new_hadj = min(self.prev_hadj - dx, hadj.upper - hadj.page_size)
        new_vadj = min(self.prev_vadj - dy, vadj.upper - vadj.page_size)
        hadj.set_value(new_hadj)
        vadj.set_value(new_vadj)
        return True

    def on_resize(self, widget, alloc):
        width = widget.get_hadjustment().page_size
        height = widget.get_vadjustment().page_size
        if widget.parent.get_current_page() != pympc.TABS['cover']:
            return
        if self.mode == 'fit':
            view_ar = width / float(height)
            if view_ar < self.pixbuf_ar:
                new_size = (int(width), int(width / self.pixbuf_ar))
            else:
                new_size = (int(height*self.pixbuf_ar), int(height))
            scaled = self.pixbuf.scale_simple(new_size[0], new_size[1], gtk.gdk.INTERP_BILINEAR)
            self.w('image').set_from_pixbuf(scaled)
        else:
            self.w('image').set_from_pixbuf(self.pixbuf)

    def on_button_press(self, widget, event):
        if event.button == 3:
            w = self.gui_popup.get_widget
            show_front  = self.covers['front'] != []
            show_back   = self.covers['back']  != []
            show_other  = self.covers['other'] != []
            w('front').set_sensitive(show_front)
            w('back').set_sensitive(show_back)
            w('other').set_sensitive(show_other)
            if show_other:
                cover_menu = gtk.Menu()
                w('other').set_submenu(cover_menu)
                for cover in self.covers['other']:
                    item = gtk.MenuItem(os.path.basename(cover))
                    item.connect('activate', self.on_cover_other, cover)
                    cover_menu.append(item)
                cover_menu.show_all()
            w('cover_popup').popup(None, None, None, event.button, event.time)
        elif event.button == 1:
            self.prev_x = event.x_root
            self.prev_y = event.y_root
            self.prev_hadj = widget.get_hadjustment().get_value()
            self.prev_vadj = widget.get_vadjustment().get_value()
        return True

    def on_cover_front(self, action):
        self.__set_type('front')
    def on_cover_back(self, action):
        self.__set_type('back')
    def on_cover_other(self, menuitem, filename):
        self.__set_type('other', filename)
    def on_cover_best_fit(self, action):
        self.mode = 'fit'
        self.w('cover_root').queue_resize()
    def on_cover_normal_size(self, action):
        self.mode = 'normal'
        self.w('cover_root').queue_resize()
    def load_file(self, cover):
        try:
            if cover != None:
                self.pixbuf = gtk.gdk.pixbuf_new_from_file(cover)
            else:
                self.pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, 1, 1)
                self.pixbuf.fill(0x00000000)
        except gobject.GError:
            self.pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, 1, 1)
            self.pixbuf.fill(0x00000000)
        self.pixbuf_ar = self.pixbuf.get_width() / float(self.pixbuf.get_height())
        self.w('cover_root').queue_resize()
