# GNU Solfege - eartraining for GNOME
# Copyright (C) 2000, 2001, 2002, 2003  Tom Cato Amundsen
#
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import os

import gtk, gnome
import gu, widgets
import mpd, mpd.musicdisplayer
import abstract, const, lessonfile
from soundcard.rat import Rat
import soundcard
import utils
import configureoutput
import dataparser

class Teacher(abstract.LessonbasedTeacher):
    """
    The Teacher and Gui for dictation abuses q_status a little.
    QSTATUS_NEW mean that the lessonfile is ok.
    QSTATUS_NO mean that the question is corrupt and unusable. Other
               questions in the same file might be useable.
    """
    def __init__(self, exname, app):
        abstract.LessonbasedTeacher.__init__(self, exname, app, const.USE_DICTATION)
        self.lessonfileclass = lessonfile.DictationLessonfile
        try:
            self.parse_lessonfile()
        except dataparser.DataparserException, e:
            self.m_app.m_ui.display_error_message(str(e))
        else:
            #to please abstract.LessonParser
            self.q_status = const.QSTATUS_NEW

class Gui(abstract.LessonbasedGui):
    def __init__(self, teacher, window):
        abstract.LessonbasedGui.__init__(self, teacher, window)
        ################
        # practise_box #
        ################
        self.g_question_title = gu.bLabel(self.practise_box, "")

        self.g_music_displayer = mpd.musicdisplayer.MusicDisplayer(utils.play_tone)
        self.g_music_displayer.show()
        self.practise_box.pack_start(self.g_music_displayer)
        ###############
        # action_area #
        ###############
        self.g_partbox = gu.bHBox(self.practise_box, gtk.FALSE)
        b = gtk.Button(stock='gtk-go-back')
        b.connect('clicked', self.select_previous)
        b.show()
        if configureoutput.WITH_GNOME:
            b.get_children()[0].get_children()[0].get_children()[1].hide()
        self.action_area.pack_start(b, gtk.FALSE)
        b = gtk.Button(stock='gtk-go-forward')
        b.show()
        b.connect('clicked', self.select_next)
        if configureoutput.WITH_GNOME:
            b.get_children()[0].get_children()[0].get_children()[1].hide()
        self.action_area.pack_start(b, gtk.FALSE)
        self.g_play = gu.bButton(self.action_area, _("_Play the whole music"),
                                 self.play)
        self.g_show = gu.bButton(self.action_area, _("_Show"), self.show_answer)
        ##############
        # config_box #
        ##############
        self.g_lessonfile_selector = widgets.SelectLessonfileWidget(
              self.m_t, self.g_win, self.update_gui_after_lessonfile_change)
        self.g_lessonfile_selector.show()
        self.config_box.pack_start(self.g_lessonfile_selector)
        self.update_gui_after_lessonfile_change()
    def select_previous(self, widget):
        self.m_t.m_P.select_previous()
        try:
            self.display_start_of_music()
        except mpd.MpdException, e:
            self.g_win.display_question_music_error_message(
                self.m_t.m_P._idx, self.get_string('lessonfile'), e)
            self.m_t.q_status = const.QSTATUS_NO
            self.g_play.set_sensitive(gtk.FALSE)
            self.g_show.set_sensitive(gtk.FALSE)
            self.g_music_displayer.clear()
        else:
            self.m_t.q_status = const.QSTATUS_NEW
            self.g_play.set_sensitive(gtk.TRUE)
            self.g_show.set_sensitive(gtk.TRUE)
        self._update()
    def select_next(self, widget):
        self.m_t.m_P.select_next()
        try:
            self.display_start_of_music()
        except mpd.MpdException, e:
            self.g_win.display_question_music_error_message(
                self.m_t.m_P._idx, self.get_string('lessonfile'), e)
            self.m_t.q_status = const.QSTATUS_NO
            self.g_play.set_sensitive(gtk.FALSE)
            self.g_show.set_sensitive(gtk.FALSE)
            self.g_music_displayer.clear()
        else:
            self.m_t.q_status = const.QSTATUS_NEW
            self.g_play.set_sensitive(gtk.TRUE)
            self.g_show.set_sensitive(gtk.TRUE)
        self._update()
    def play(self, widget=None):
        # see Teacher docstring.
        if self.m_t.q_status != const.QSTATUS_NEW:
            return
        if not self.m_t.m_P:
            return
        try:
            self.m_t.play_question()
        except mpd.MpdException, e:
            # since we could not play the new question, it is possible,
            # if the user are fast, that the last question is still playing.
            soundcard.synth.stop()
            self.g_win.display_question_music_error_message(
                self.m_t.m_P._idx, self.get_string('lessonfile'), e)
    def on_end_practise(self):
        self.m_t.end_practise()
        self.update_gui_after_lessonfile_change()
    def show_answer(self, widget=None):
        # see Teacher docstring.
        if self.m_t.q_status != const.QSTATUS_NEW:
            return
        if not self.m_t.m_P:
            return
        try:
            self.g_music_displayer.display(self.m_t.m_P.get_music(),
                            self.get_int('config/feta_font_size=20'))
        except mpd.MpdException, e:
            self.g_win.display_question_music_error_message(
                self.m_t.m_P._idx, self.get_string('lessonfile'), e)
    def _update(self):
        """
        Updates the buttons above the action_area where you have
        one or more buttons with a small note pixmap on. Each of the
        buttons will play one part of the music in the question.
        """
        # tmp func used as callback function
        def f(w, start, end, self=self):
            try:
                track = mpd.music_to_track(self.m_t.m_P.get_music(),
                       self.get_int('config/preferred_instrument_velocity'),
                       start, end)
                apply(track.prepend_bpm, self.m_t.m_P.get_tempo())
                track.prepend_patch(0, self.get_int('config/preferred_instrument'))
                soundcard.synth.play_track(track)
            except mpd.MpdException, e:
                soundcard.synth.stop()
                self.g_win.display_question_music_error_message(
                   self.m_t.m_P._idx, self.get_string('lessonfile'), e)
        for i in self.g_partbox.get_children():
            i.destroy()
        # if the user selects a collection without lessonfiles, or if
        # the lessonfile was invalid, m_P could be None
        if self.m_t.m_P:
            self.g_question_title.set_text(self.m_t.m_P.get_name())
            v = self.m_t.m_P.get_breakpoints()
            if v == []:
                # we display one button that will play the whole music if
                # there are not breakpoints in the music
                btn = self.create_pixmap_button()
                btn.connect('clicked', f, None, None)
                btn.show()
                self.g_partbox.pack_start(btn)
                return
            tmp = [Rat(0, 1)] + v + [Rat(2**30, 1)]
            for i in range(len(tmp) - 1):
                btn = self.create_pixmap_button()
                btn.show()
                btn.connect('clicked', f, tmp[i], tmp[i+1])
                self.g_partbox.pack_start(btn)
        # q_status is QSTATUS_NO if the question is invalid (from the lessonfile)
        if self.m_t.q_status == const.QSTATUS_NO:
            self.g_partbox.set_sensitive(gtk.FALSE)
        else:
            self.g_partbox.set_sensitive(gtk.TRUE)
    def display_start_of_music(self):
        fontsize = self.get_int('config/feta_font_size=20')
        if self.m_t.m_P.get_clue_music():
                self.g_music_displayer.display(self.m_t.m_P.get_clue_music(),
                                               fontsize)
        elif self.m_t.m_P.get_clue_end():
                self.g_music_displayer.display_range(self.m_t.m_P.get_music(),
                               fontsize, Rat(0, 1), self.m_t.m_P.get_clue_end())
        else:
                self.g_music_displayer.display(self.m_t.m_P.get_music(),
                                               fontsize, mpd.FIRST)
    def update_gui_after_lessonfile_change(self):
        self.m_t.q_status = const.QSTATUS_NEW
        if self.m_t.m_P:
            self.action_area.set_sensitive(gtk.TRUE)
            try:
                self.display_start_of_music()
            except mpd.MpdException, e:
                self.g_win.display_question_music_error_message(
                    self.m_t.m_P._idx, self.get_string('lessonfile'), e)
                self.m_t.q_status = const.QSTATUS_NO
                self.g_play.set_sensitive(gtk.FALSE)
                self.g_show.set_sensitive(gtk.FALSE)
                self.g_music_displayer.clear()
            else:
                self.g_play.set_sensitive(gtk.TRUE)
                self.g_show.set_sensitive(gtk.TRUE)
        else:
            self.g_music_displayer.clear()
            self.action_area.set_sensitive(gtk.FALSE)
        self._update()
        self.g_win.set_title("Solfege - " + self.get_pretty_name())
    def create_pixmap_button(self):
        im = gtk.Image()
        im.set_from_file(os.path.join("graphics", "rhythm-c4.png"))
        btn = gtk.Button()
        btn.add(im)
        im.show()
        return btn
    def on_start_practise(self):
        self.g_play.grab_focus()

