#!/usr/bin/env python

#  CoverGloobus by BadChoice <guitarboy000@gmail.com>
#  - Reused a lot of code from NowPlaying Screenlet done by Magicrobomonkey and modified by Vrunner
#
# INFO:
# - a simple viewer for currently playing and lyrics searcher
# - Webpage: http://launchpad.net/covergloobus
# - Blog:     http://gloobus.wordpress.com
# - Donate:  guitarboy000@gmail.com via PayPal
# 
# TODO:
#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 2
#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, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#import ConfigParser
#import os
#import sys
#import glob
import gtk
#import signal
#from colors import *
#import gettext
#import config
import common
import widgets

#from common import c

"""
class CoverGloobusConfig(gtk.Window): 
    def __init__(self):
        gtk.Window.__init__(self, parent = None)

        self._parent = parent

        self.config = common.config_load()
        self.themes = common.get_themes()
        self.current_theme = common.Theme(self.config.get("Theme","name"), 
            self.config.get("Theme","path"))
        c.debug('Current theme: ' + self.current_theme.path)

        self.set_title(_('CoverGloobus Configuration'))
        self.set_icon_from_file(common.ICON_PATH)
        
        self.connect('destroy', gtk.main_quit)
        self.connect('delete_event', gtk.main_quit)
        self.set_position(gtk.WIN_POS_CENTER)
        
        self.notebook = gtk.Notebook()
        self.notebook.set_border_width(5)
        self.notebook.set_tab_pos(gtk.POS_LEFT)

        self.container = gtk.VBox()

        self.make_pages()
        self.make_buttons()
        
        self.add(self.container)
        self.show_all()

    def make_pages(self):
        self.pages = {}
        for name in pages:
            method = getattr(self, 'make_'+name)
            page = method()
            label = gtk.Label(_(name))
            valign = gtk.Alignment(0, 0, 0, 0)
            valign.add(page)
            valign.set_border_width(10)
            valign.set_size_request(400, 300)
            self.notebook.append_page(valign, label)
            self.pages[name] = page
        self.container.add(self.notebook)

    def make_buttons(self):
        save = gtk.Button(stock=gtk.STOCK_SAVE)
        save.set_size_request(100,25)
        cancel = gtk.Button(stock=gtk.STOCK_CANCEL)
        cancel.set_size_request(100,25)
        save.connect('clicked', self.save_config)
        #cancel.connect("clicked", gtk.main_quit)
        cancel.connect("clicked", self.cancel)
        
        buttons = gtk.HBox()
        buttons.set_border_width(5)
        buttons.set_spacing(10)
        buttons.add(cancel)
        buttons.add(save)
        
        halign = gtk.Alignment(1, 0, 0, 0)
        halign.add(buttons)
        self.container.add(halign)

    def make_General(self):
        box = gtk.VBox()

        #============= SHOW STATUS ICON ================ #
        self.check_status_icon = gtk.CheckButton(label=_("Show Status Icon"), use_underline=False)
        c.debug("Show status icon:" + str(bool(self.config.get("StatusIcon","value"))))
        self.check_status_icon.set_active(self.config.getint("StatusIcon","value"))
        box.add(self.check_status_icon)

        #=============== ENABLE AMAZON ================== #
        self.check_amazon = gtk.CheckButton(label=_("Enable Amazon Covers"), use_underline=False)
        c.debug("Amazon Covers:" + str(self.config.getboolean("AmazonCovers","value")))
        self.check_amazon.set_active(self.config.getboolean("AmazonCovers","value"))
        box.add(self.check_amazon)

        #=============== ENABLE DOCKY ================== #
        self.check_docky = gtk.CheckButton(label=_("Enable Covers on Docky"), use_underline=False)
        c.debug("Docky:" + str(self.config.getboolean("Docky","value")))
        self.check_docky.set_active(self.config.getboolean("Docky","value"))
        box.add(self.check_docky)

        #=================== PLAYER ================== #
        box_player = gtk.HBox()
        label_player = gtk.Label(_("Player:"))
        label_player.set_size_request(150,30)
        self.entry_player = gtk.combo_box_new_text()
        self.entry_player.set_size_request(200,30)
        players = common.get_players()
        current = self.config.get("Player","name")
        for i in range(len(players)):
            self.entry_player.append_text(players[i])
            if players[i] == current:
                self.entry_player.set_active(i)
                c.debug("Active:" + players[i])
        box_player.add(label_player)
        box_player.add(self.entry_player)
        box.add(box_player)
        
        return box

    def make_Window(self):
        table = gtk.Table(10, 2, True)
        table.set_col_spacings(10)

        #================= X START POS ================= #
        self.entry_pos_x = gtk.Entry(5)
        self.entry_pos_x.set_text(self.config.get('StartPosition','x'))
        table.attach(gtk.Label(_("Start Position x:")), 0, 1, 0, 1)
        table.attach(self.entry_pos_x, 1, 2, 0, 1)

        #================= Y START POS ================= #
        self.entry_pos_y = gtk.Entry(5)
        self.entry_pos_y.set_text(self.config.get('StartPosition','y'))
        table.attach(gtk.Label(_("Start Position y:")), 0, 1, 1, 2)
        table.attach(self.entry_pos_y, 1, 2, 1, 2)

        #=============== ALLWAYS ON TOP ================== #
        self.check_ontop = gtk.CheckButton(label=_("Always on top"), use_underline=False)
        c.debug("On Top:" + str(self.config.getboolean("StartPosition","ontop")))
        self.check_ontop.set_active(self.config.getboolean("StartPosition","ontop"))
        table.attach(self.check_ontop, 0, 2, 2, 3)

        #============= STICK TO DESKTOP ================ #
        self.check_stick = gtk.CheckButton(label=_("Stick to Desktop"), use_underline=False)
        c.debug("Stick to desktop:" + str(self.config.getboolean("DesktopStick","value")))
        self.check_stick.set_active(self.config.getboolean("DesktopStick","value"))
        table.attach(self.check_stick, 0, 2, 3, 4)

        #============= SHOW BACKGROUND ================= #
        self.check_background = gtk.CheckButton(label=_("Show Background"), use_underline=False)
        c.debug("Show background:" + str(bool(self.config.get("Background","show"))))
        self.check_background.set_active(self.config.getint("Background","show"))
        table.attach(self.check_background, 0, 2, 4, 5)

        #============== BACKGROUND OPACITY ============== #
        label_opacity = gtk.Label(_("Background opacity:"))
        adjustment = gtk.Adjustment(self.config.getfloat("Background","opacity"), 0.1, 1, 0.1, 0.1)
        self.spin_opacity = gtk.SpinButton(adjustment, 0.1, 1)
        table.attach(label_opacity, 0, 1, 5, 6)
        table.attach(self.spin_opacity, 1, 2, 5, 6)

        return table

    def make_Theme(self):
        box = gtk.VBox()

        box_theme = gtk.HBox()
        label_theme = gtk.Label(_("Theme:"))
        label_theme.set_size_request(125,30)
        self.entry_theme = gtk.combo_box_new_text()
        self.entry_theme.set_size_request(250,30)
        for theme in self.themes:
            self.entry_theme.append_text(theme.name)
            if theme.path == self.current_theme.path:
                self.entry_theme.set_active(self.themes.index(theme))
                c.debug("Active: " + theme.name)
            
        box_theme.add(label_theme)
        box_theme.add(self.entry_theme)

        box_image = gtk.HBox()
        self.image = gtk.Image()
        self.change_theme(self)
        self.entry_theme.connect('changed',self.change_theme)
        align = gtk.Alignment(0.5, 0.5, 0, 0)
        align.set_size_request(375, 250)
        align.add(self.image)
        box_image.add(align)

        box.add(box_theme)
        box.add(box_image)
        
        return box

    def make_Lyrics(self):
        box = gtk.VBox()

        #=================== LYRICS ================== #
        box_lyrics = gtk.HBox()
        label_lyrics = gtk.Label(_("Lyric Engine:"))
        label_lyrics.set_size_request(175,30)
        label_lyrics.set_alignment(0.0, 0.5)
        self.entry_lyrics = gtk.combo_box_new_text()
        self.entry_lyrics.set_size_request(200,30)
        engines = common.get_lyric_engines()
        current = self.config.get("Lyrics","name")
        for i in range(len(engines)):
            self.entry_lyrics.append_text(engines[i])
            if engines[i] == current:
                self.entry_lyrics.set_active(i)
                c.debug("Active:" + engines[i])
        box_lyrics.add(label_lyrics)
        box_lyrics.add(self.entry_lyrics)
        box.add(box_lyrics)
        
        #=================== TABS ================== #
        box_tabs = gtk.HBox()
        label_tabs = gtk.Label(_("Tab Engine:"))
        label_tabs.set_size_request(175,30)
        label_tabs.set_alignment(0.0, 0.5)
        self.entry_tabs = gtk.combo_box_new_text()
        self.entry_tabs.set_size_request(200,30)
        engines = common.get_tab_engines()
        current = self.config.get("Tabs","name")
        for i in range(len(engines)):
            self.entry_tabs.append_text(engines[i])
            if engines[i] == current:
                self.entry_tabs.set_active(i)
                c.debug("Active:" + engines[i])
        box_tabs.add(label_tabs)
        box_tabs.add(self.entry_tabs)
        box.add(box_tabs)

        self.check_lyrics_try_all = gtk.CheckButton(label=_("Try other engines if nothing found"), use_underline=False)
        self.check_lyrics_try_all.set_active(self.config.getboolean("Lyrics","try_all"))
        box.add(self.check_lyrics_try_all)

        #=================== WINDOW TARGET ================== #
        self.lyric_window_targets = [
            ('new'     , 'New window'),
            ('separate', 'Separate windows'),
            ('shared'  , 'Same window')
        ]
        box_window = gtk.HBox()
        label_window = gtk.Label(_("Open lyrics and tabs in:"))
        label_window.set_size_request(175,30)
        label_window.set_alignment(0.0, 0.5)
        self.entry_lyric_window = gtk.combo_box_new_text()
        self.entry_lyric_window.set_size_request(200,30)
        current = self.config.get("Lyrics","window")
        i = 0
        for entry in self.lyric_window_targets:
            self.entry_lyric_window.append_text(entry[1])
            if entry[0] == current:
                self.entry_lyric_window.set_active(i)
            i = i + 1
        box_window.add(label_window)
        box_window.add(self.entry_lyric_window)
        box.add(box_window)

        self.check_lyrics_widget = gtk.CheckButton(label=_("Show lyrics windows as widget"), use_underline=False)
        self.check_lyrics_widget.set_active(self.config.getboolean("Lyrics","widget"))
        box.add(self.check_lyrics_widget)

        self.check_lyrics_refresh = gtk.CheckButton(label=_("Refresh lyrics/tabs when song changes"), use_underline=False)
        self.check_lyrics_refresh.set_active(self.config.getboolean("Lyrics","refresh"))
        box.add(self.check_lyrics_refresh)

        self.check_lyrics_cache = gtk.CheckButton(label=_("Cache lyrics/tabs"), use_underline=False)
        self.check_lyrics_cache.set_active(self.config.getboolean("Lyrics","cache"))
        box.add(self.check_lyrics_cache)
        
        return box

    def make_MPD(self):
        box = gtk.VBox()
        h = 30
        wlabel = 100
        wentry = 250

        box_host = gtk.HBox()
        label_host = gtk.Label(_("Host:"))
        label_host.set_size_request(wlabel,h)
        self.entry_mpd_host = gtk.Entry()
        self.entry_mpd_host.set_size_request(wentry,h)
        self.entry_mpd_host.set_text(self.config.get('MPD','host'))
        box_host.add(label_host)
        box_host.add(self.entry_mpd_host)

        box_port = gtk.HBox()
        label_port = gtk.Label(_("Port:"))
        label_port.set_size_request(wlabel,h)
        self.entry_mpd_port = gtk.Entry()
        self.entry_mpd_port.set_size_request(wentry,h)
        self.entry_mpd_port.set_text(self.config.get('MPD','port'))
        box_port.add(label_port)
        box_port.add(self.entry_mpd_port)

        box_pass = gtk.HBox()
        label_pass = gtk.Label(_("Password:"))
        label_pass.set_size_request(wlabel,h)
        self.entry_mpd_pass = gtk.Entry()
        self.entry_mpd_pass.set_size_request(wentry,h)
        self.entry_mpd_pass.set_text(self.config.get('MPD','password'))
        box_pass.add(label_pass)
        box_pass.add(self.entry_mpd_pass)

        box_path = gtk.HBox()
        label_path = gtk.Label(_("Library:"))
        label_path.set_size_request(wlabel,h)
        self.entry_mpd_path = gtk.Entry()
        self.entry_mpd_path.set_size_request(wentry,h)
        self.entry_mpd_path.set_text(self.config.get('MPD','path'))
        box_path.add(label_path)
        box_path.add(self.entry_mpd_path)

        box.add(box_host)
        box.add(box_port)
        box.add(box_pass)
        box.add(box_path)
        
        return box

    # ====================================================================== #
    def change_theme(self,widget):
        width = 375
        height = 250
        try:
            pic = gtk.gdk.pixbuf_new_from_file(
                self.themes[self.entry_theme.get_active()].path + 
                "/screenshot.png")
        except:
            pic = gtk.gdk.pixbuf_new_from_file(common.ABS_PATH + 
                "/themes/noscreenshot.png")

        resize = False
        ratio = 0
        w = pic.get_width()
        h = pic.get_height()
        if w > width:
            ratio = float(w) / float(width)
        if h > height:
            r = float(h) / float(height)
            if r > ratio:
                ratio = r
        if ratio:
            pic = pic.scale_simple(int(w/ratio), int(h/ratio), gtk.gdk.INTERP_BILINEAR)
        self.image.set_from_pixbuf(pic)

    def save_config(self,button):
        c.info(c.color('brown', _('Saving new configuration')))
        c.debug("x:" + self.entry_pos_x.get_text())
        c.debug("y:" + self.entry_pos_y.get_text())
        c.debug("Theme:" + self.entry_theme.get_active_text())
        c.debug("Player:" + self.entry_player.get_active_text())
        c.debug("Lyrics:" + self.entry_lyrics.get_active_text())
        c.debug("Tabs:" + self.entry_tabs.get_active_text())
        c.debug("Ontop:" + str(int(self.check_ontop.get_active())))
        c.debug("Amazon Covers:" + str(int(self.check_amazon.get_active())))
        c.debug("Docky:" + str(int(self.check_docky.get_active())))
        c.debug("Stick to desktop:" + str(int(self.check_stick.get_active())))
        c.debug("Show status icon:" + str(int(self.check_status_icon.get_active())))
        c.debug("Show background:" + str(int(self.check_background.get_active())))
        c.debug("Background opacity:" + str(self.spin_opacity.get_value()))
        
        self.config.set('StartPosition', 'x', self.entry_pos_x.get_text())
        self.config.set('StartPosition', 'y', self.entry_pos_y.get_text())
        self.config.set('StartPosition', 'ontop', str(int(self.check_ontop.get_active())))
        self.config.set('Theme', 'name', self.themes[self.entry_theme.get_active()].name)
        self.config.set('Theme', 'path', self.themes[self.entry_theme.get_active()].path)
        self.config.set('Player', 'name', self.entry_player.get_active_text())        
        self.config.set('Lyrics', 'name', self.entry_lyrics.get_active_text())
        self.config.set('Tabs', 'name', self.entry_tabs.get_active_text())
        self.config.set('AmazonCovers', 'value', str(int(self.check_amazon.get_active())))
        self.config.set('Docky', 'value', str(int(self.check_docky.get_active())))
        self.config.set('DesktopStick', 'value', str(int(self.check_stick.get_active())))
        self.config.set('StatusIcon', 'value', str(int(self.check_status_icon.get_active())))
        self.config.set('Background', 'show', str(int(self.check_background.get_active())))
        self.config.set('Background', 'opacity', str(self.spin_opacity.get_value()))
        self.config.set('MPD', 'host', self.entry_mpd_host.get_text())
        self.config.set('MPD', 'port', self.entry_mpd_port.get_text())
        self.config.set('MPD', 'password', self.entry_mpd_pass.get_text())
        self.config.set('MPD', 'path', self.entry_mpd_path.get_text())
        self.config.set('Lyrics', 'try_all', str(int(self.check_lyrics_try_all.get_active())))
        self.config.set('Lyrics', 'window', self.lyric_window_targets[self.entry_lyric_window.get_active()][0])
        self.config.set('Lyrics', 'widget', str(int(self.check_lyrics_widget.get_active())))
        self.config.set('Lyrics', 'refresh', str(int(self.check_lyrics_refresh.get_active())))
        self.config.set('Lyrics', 'cache', str(int(self.check_lyrics_cache.get_active())))

        common.config_save(self.config)
        
        #try:
            #if pid:
                #os.kill(int(pid),signal.SIGUSR1)
        #except:
            #pass
        if self._parent:
            self.parent.init()
        self.destroy()
        #gtk.main_quit()

    def cancel(self):
        if not self._parent:
            gtk.main_quit()
        else:
            self.destroy()
"""
# ============================================================================ #

if __name__ == "__main__":
    #TRANSLATIONS
    #gettext.bindtextdomain('covergloobus', config.prefix+'/share/locale/')
    #gettext.textdomain('covergloobus')
    #_ = gettext.gettext

    #debug = False
    #pid = None
    #c = colors()

    """
    #Know the pid to restart covergloobus
    try:
        for i in range(len(sys.argv)):
            if i == 0:
                continue
            if sys.argv[i] == "--debug":
                c.set_debug(True)
                debug=True
            else:
                pid = int(sys.argv[i])
        if pid == None:
            pid = common.get_pid()
    except:
        pid = None

    if pid == None:
        c.info(_("Running config in standalone mode"))
    
    c.debug("Prefix: " + config.prefix)
    c.debug("Path: "   + common.ABS_PATH)
    if(debug):
        c.debug('Installed themes:')
        for theme in common.get_themes():
            print theme, ',',
        print '\n',
        c.debug('Installed players:')
        print common.get_players()
        c.debug('Installed lyrics search engines:')
        print common.get_lyric_engines()
        c.debug('Installed tabs search engines:')
        print common.get_tab_engines()
    """
    widgets.CoverGloobusConfig()
    gtk.main()

