#!/usr/bin/python
# -*- coding: UTF8 -*-

# -----------------------------------------------------------------------------
# Tux Droid - song change script
# Copyright (C) 2007 Vincent Fretin <vincent.fretin@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 2, 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., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
# -----------------------------------------------------------------------------

"""
Read currently played song.

Use this script with song_change plugin of audacious media player (http://audacious-media-player.org)
Put this script somewhere, for example in /usr/local/bin/ 
and in audacious, put in song_change preferences: /usr/local/bin/song_change.py "%s"


This script can be used while listening a radio with audacious.
You need to compile audacious-plugins with
"#define DEBUG_METADATA_REPORT 1"
in the file audacious-plugins-1.3.2/src/curl/curl.c
to print the artist-title in the terminal
When the radio play a new song, in the terminal, you will have for example: 
New song: 'PENICILLIN - Prision'

You have to launch audacious like this:
audacious |tee /tmp/audacious-radio
and you have to launch the script in an other terminal: song_change.py
This script have been tested with shinsen-radio (http://www.shinsen-radio.org)

Download the filetail module at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/436477
Put it near song_change.py or in Python path.

CHANGES
=======
2007/04/21 - version 1.0:
    - initial version
"""

__author__ = "Vincent Fretin (vincent.fretin@gmail.com)"
__version__ = "1.0"
__date__ = "2007/04/19"
__copyright__ = "Copyright (C) 2007 Vincent Fretin"
__license__ = "GPL2+"


import sys
sys.path.append('/opt/tuxdroid/api/python')
from tux import *

# -----------------------------------------------
# Your script
# -----------------------------------------------


#SELECTED_LANGUAGE="fr"
SELECTED_LANGUAGE="en"
current_artist_title="artist-title"

def read_current_title_and_artist():
    """
    Read currently played song. (in radio mode)
    """
    global current_artist_title
    print "read current song",current_artist_title
    read_title_and_artist(current_artist_title)


def remove_album(song):
    """
    Remove the album information from the string song.

    song is a string like this: "artist - album - title"
    It's the string given by audacious with %s in audacious's song_change plugin
    Return a string "artist-title"
    """
    parts = song.split(" - ")
    return parts[0].strip()+"-"+parts[2].strip()


def read_title_and_artist(artist_title):
    """
    Read the title and album of the song if the current song is different of 
    those in parameter.
    """

    global SELECTED_LANGUAGE
    global current_artist_title
    # keep in memory the current song
    current_artist_title = artist_title.replace("_"," ").replace("~"," ")
#    s = current_artist_title
#    s = s.lower()
#    s = s.replace("he","hey")
#    s = s.replace("hi","hee")
#    s = s.replace("ne","ney")
#    s = s.replace("ue","u hey")
#    artist, title = s.split("-",1)
    artist, title = current_artist_title.split('-',1)

    tux.cmd.mouth_open()

    if SELECTED_LANGUAGE == "fr":
        print "Tu écoutes " + title + ", " + artist
        tux.tts.select_voice_fr_male_tuxed()
        tux.tts.speak_free("Tu écoutes.")
        tux.sys.wait(0.6)
        tux.tts.select_voice_us_male_tuxed()
        tux.tts.speak(title+".")
        tux.sys.wait(0.2)
#       tux.tts.select_voice_fr_male_tuxed()
#       tux.tts.speak_free("de.")
#       tux.sys.wait(0.2)
        tux.tts.select_voice_us_male_tuxed()
        tux.tts.speak(artist+".")
    else:
        to_tts = "You are listening. "+title+". From "+artist+"."
        print to_tts
        tux.tts.select_voice_us_male_tuxed()
        tux.tts.speak(to_tts)

    tux.cmd.mouth_close()
    tux.sys.wait(1)



if __name__ == "__main__":
    if len(sys.argv) < 2: # Without arguments, we are playing a radio
        try:
            import filetail
        except ImportError:
            print "You need filetail.py from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/436477 to use the script with a radio"
        else:
            tux.sys.shell("touch /tmp/audacious-radio")
            t = filetail.Tail("/tmp/audacious-radio", only_new=True, max_sleep=10)
            tux.event.on_head_bt_pushed = read_current_title_and_artist
            while True:
                line = t.nextline()
                # do something with the line
                # a line looks like this:
                # New song: 'PENICILLIN - Prision'\n
                # New song: 'PENICILLIN - Prision -  Request at http://www.shinsen-radio.org'\n
                if (line.find("New song:") != -1) and (line.find("-") != -1):
                    s = line.split("'",1); # PENICILLIN - Prision'\n
                    artist_title = s[1].rsplit("'",1)[0] # PENICILLIN - Prision
                    if (line.find("Request") != -1): # shinsen-radio specific
                        parts = artist_title.split(" - ",2)
                        artist_title = parts[0].strip()+" - "+parts[1].strip()
                    # do nothing if the song is the same.
                    if current_artist_title != artist_title:
                        read_title_and_artist(artist_title)
    else: # we use song_change
        if sys.argv[1].count(" - ") == 1:   # if audacious was configured with: artist - title
            print sys.argv[1]
            read_title_and_artist(sys.argv[1])
        elif sys.argv[1].count(" - ") >= 2: # audacious normal mode: artist - album - title
            print sys.argv[1]
            read_title_and_artist(remove_album(sys.argv[1]))


# -----------------------------------------------
# End of script
# -----------------------------------------------
tux.destroy()
