#!/usr/bin/python2
try:
    from gi.repository import Gtk
    from gi.repository import Gdk
except ImportError:
    exit('You need to install the "python-gobject" library.')

import os
import sys
import subprocess

from cherrymusicserver import pathprovider
from cherrymusicserver import configuration as cfg
from cherrymusicserver import CherryMusic


class CherryMusicTrayIcon:
    def __init__(self):
        self.statusicon = Gtk.StatusIcon()
        self.execpath = os.path.dirname(__file__)
        self.icon_path = pathprovider.getResourcePath('res/img/tray-icon.png')
        self.cherry_image = Gtk.Image.new_from_file(self.icon_path)
        self.icon_set = Gtk.IconSet(self.cherry_image.get_pixbuf())
        self.statusicon.set_from_file(self.icon_path)
        self.statusicon.connect("popup-menu", self.right_click_event)
        self.statusicon.connect("button-press-event", self.left_click_event)
        self.statusicon.set_visible(True)
        filecfg = cfg.from_configparser(pathprovider.configurationFile())
        self.cmport = filecfg['server.port']
        self.cmexec = os.path.join(self.execpath, 'cherrymusic')

    def is_running(self):
        return pathprovider.pidFileExists()

    def start_cherrymusic(self, widget, data=None):
        print('executing %s'%self.cmexec)
        subprocess.Popen([self.cmexec])

    def stop_cherrymusic(self, widget, data=None):
        with open(pathprovider.pidFile(), 'r') as pidfh:
            pid = pidfh.read()
            subprocess.call(['kill', pid])
            subprocess.call(['kill', pid])
            CherryMusic.delete_pid_file()

    def show_cherrymusic(self, widget, data=None):
        url =  'http://localhost:' + self.cmport
        subprocess.call(['xdg-open', url])

    def left_click_event(self, widget, event):
        if event.type == Gdk.EventType._2BUTTON_PRESS:
            if self.is_running():
                self.show_cherrymusic(None)

    def right_click_event(self, icon, button, time):
        self.menu = Gtk.Menu()
        running = self.is_running()

        btn_show = Gtk.ImageMenuItem('Show CherryMusic in browser')
        #btn_show.set_image(icon_img)
        btn_show.connect('activate', self.show_cherrymusic)
        btn_show.set_sensitive(1 if running else 0)
        self.menu.append(btn_show)

        btn_start = Gtk.ImageMenuItem('Start server')
        btn_start.set_image(self.cherry_image)
        btn_start.connect('activate', self.start_cherrymusic)
        btn_start.set_sensitive(0 if running else 1)
        self.menu.append(btn_start)

        btn_stop = Gtk.ImageMenuItem('Stop server')
        btn_stop.connect('activate', self.stop_cherrymusic)
        btn_stop.set_sensitive(1 if running else 0)
        self.menu.append(btn_stop)

        self.menu.append(Gtk.SeparatorMenuItem())

        btn_about = Gtk.MenuItem("About")
        btn_about.connect("activate", self.show_about_dialog)
        self.menu.append(btn_about)

        btn_quit = Gtk.ImageMenuItem("Quit")
        btn_quit.set_use_stock(True)
        btn_quit.connect("activate", Gtk.main_quit)
        self.menu.append(btn_quit)

        self.menu.show_all()

        def pos(menu, icon):
                return (Gtk.StatusIcon.position_menu(menu, icon))

        self.menu.popup(None, None, pos, self.statusicon, button, time)

    def show_about_dialog(self, widget):
        about_dialog = Gtk.AboutDialog()

        about_dialog.set_destroy_with_parent(True)
        about_dialog.set_program_name('cherrymusic-tray')
        about_dialog.set_comments("start/stop your CherryMusic server comfortably.")
        about_dialog.set_license(_get_license())
        about_dialog.set_version("0.1")
        about_dialog.set_authors(["Tom Wallroth"])

        about_dialog.run()
        about_dialog.destroy()


def _get_license():
    licenseFile = pathprovider.licenseFile()
    try:
        with open(licenseFile, 'r') as licensing:
            license = licensing.read()
    except:
        import traceback
        traceback.print_exc()
        license = 'Unable to read license file {0!r}.\nPlease see {1}'.format(
            licenseFile, 'http://www.gnu.org/licenses/gpl-3.0.html')
    finally:
        return license




if __name__ == "__main__":
    tray = CherryMusicTrayIcon()
    Gtk.main()

    #tray = CMTray()
    #tray.run()
