# 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 gtk
import gnome

import gu, widgets

import mpd
import mpd.musicdisplayer
import const
import abstract
import lessonfile
import cfg
import dataparser
import soundcard

class Teacher(abstract.LessonbasedTeacher):
    OK = 0
    ERR_PICKY = 1
    #UGH should we do this here
    def __init__(self, exname, app):
        abstract.LessonbasedTeacher.__init__(self, exname, app, const.USE_CHORD_VOICING)
        self.lessonfileclass = lessonfile.ChordLessonfile
        try: # the lessonfile might contain errors.
            self.parse_lessonfile()
        except dataparser.DataparserException, e:
            self.m_app.m_ui.display_error_message('__init__'+str(e))
    def new_question(self):
        """
        return 1 if the teacher has a question to ask
        UI will never call this function unless we have a usable lessonfile.
        """
        assert self.m_P
        if self.get_bool('config/picky_on_new_question') \
                 and not(self.q_status in (const.QSTATUS_VOICING_SOLVED, const.QSTATUS_NO)):
             return Teacher.ERR_PICKY

        if self.m_P:
            self.m_P.select_random_question()
            self.q_status = const.QSTATUS_NEW
            return Teacher.OK
    def play_question(self):
        if self.q_status == const.QSTATUS_NO:
            return
        mpd.play_music(r"\staff{ <%s> }" % self.m_P.get_music(),
                       self.m_P.get_tempo(),
                       cfg.get_int('config/preferred_instrument'),
                       cfg.get_int('config/preferred_instrument_velocity'))
    def play_question_arpeggio(self):
        if self.q_status == const.QSTATUS_NO:
            return
        mpd.play_music(r"\staff{ %s }" % self.m_P.get_music(),
                       cfg.get_int('config/arpeggio_bpm'),
                       cfg.get_int('config/preferred_instrument'),
                       cfg.get_int('config/preferred_instrument_velocity'))
    def guess_chordtype(self, t):
        """
        return 1 if correct, None if not.
        This function will set self.q_status, and will raise an
        exception if the function is called with invalid value of
        q_status.

        Before we start: const.QSTATUS_NO
        After 'New' is clicked: const.QSTATUS_NEW

        if chordtype correct: const.QSTATUS_TYPE_SOLVED
        if chordtype wrong: const.QSTATUS_TYPE_WRONG

        if voicing correct const.QSTATUS_VOICING_SOLVED
        if voicing wrong: const.QSTATUS_VOICING_WRONG
        """
        if self.q_status in (const.QSTATUS_NEW, const.QSTATUS_TYPE_WRONG):
            if t == self.m_P.get_chordtype():
                self.q_status = const.QSTATUS_TYPE_SOLVED
                return 1
            else:
                self.q_status = const.QSTATUS_TYPE_WRONG
                return
    def guess_voicing(self, tones):
        """
        return 1 if correct, None if not.
        Gui should not call this function if the question is already solved.
        """
        question_i = []
        for n in self.m_P.get_music().split():
            while n[-1] in ",'":
                n = n[:-1]
            question_i.append(mpd.notename_to_int(n))
        answer_i = []
        for n in tones:
            while n[-1] in ",'":
                n = n[:-1]
            answer_i.append(mpd.notename_to_int(n))
        if answer_i == question_i:
            self.q_status = const.QSTATUS_VOICING_SOLVED
            return 1
        self.q_status = const.QSTATUS_VOICING_WRONG
    def give_up(self):
        self.q_status = const.QSTATUS_VOICING_SOLVED

class Gui(abstract.LessonbasedGui):
    def __init__(self, teacher, window):
        abstract.LessonbasedGui.__init__(self, teacher, window)
        self.m_stacking_frame_min_height = 0
        self.set_size_request(400, -1)

        ###############
        # practise_box
        ###############
        self.practise_box.set_spacing(gnome.ui.PAD)

        hbox = gu.bHBox(self.practise_box, gtk.TRUE, gtk.TRUE)
        hbox.set_spacing(gnome.ui.PAD)
        ##################
        # chordtype frame 
        ##################
        frame = gtk.Frame(_("Identify chord type"))
        hbox.pack_start(frame)
        self.g_chordtype_box = gtk.VBox()
        self.g_chordtype_box.set_border_width(gnome.ui.PAD_SMALL)
        frame.add(self.g_chordtype_box)

        #################
        # stacking frame
        #################
        self.g_stacking_frame = gtk.Frame(_("Click to stack in the correct order"))
        self.g_stacking_frame.set_sensitive(gtk.FALSE)
        hbox.pack_start(self.g_stacking_frame)
        vbox = gtk.VBox()
        vbox.set_border_width(gnome.ui.PAD_SMALL)
        self.g_stacking_frame.add(vbox)
        t = gtk.Table(1, 1, 1)
        vbox.pack_start(t)
        self.g_source = gtk.VBox()
        t.attach(self.g_source, 0, 1, 0, 1, gtk.EXPAND|gtk.FILL)
        self.g_answer = gtk.VBox()
        t.attach(self.g_answer, 1, 2, 0, 1, gtk.EXPAND|gtk.FILL)
        self.g_redo = gtk.Button("<<<")
        self.g_redo.connect('clicked', lambda o, self=self: self.fill_stacking_frame())
        vbox.pack_end(self.g_redo, gtk.FALSE, gtk.FALSE)

        self.g_flashbar = gu.FlashBar()
        self.practise_box.pack_start(self.g_flashbar, gtk.FALSE)

        self.g_new = gu.bButton(self.action_area, _("_New chord"),
                                      self.new_question)
        self.g_repeat = gu.bButton(self.action_area, _("_Repeat"),
                 lambda _o, self=self: self.m_t.play_question())
        self.g_repeat_arpeggio = gu.bButton(self.action_area, _("Repeat _arpeggio"), lambda _o, self=self: self.m_t.play_question_arpeggio())
        self.g_give_up = gu.bButton(self.action_area, _("_Give up"), lambda _o, self=self: self.give_up())
        self.practise_box.show_all()
        ##############
        # config_box #
        ##############
        self.config_box.set_spacing(gnome.ui.PAD_SMALL)
        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 new_question(self, widget=None):
        # if we have no lessonfile, then we have no questions.
        if not self.m_t.m_P:
            return
        try:
            g = self.m_t.new_question()
        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)
            self.g_give_up.set_sensitive(gtk.FALSE)
            self.g_repeat.set_sensitive(gtk.FALSE)
            self.g_repeat_arpeggio.set_sensitive(gtk.FALSE)
            self.m_t.q_status = const.QSTATUS_NO
        else:
            if g == Teacher.OK:
                self.g_give_up.set_sensitive(gtk.TRUE)
                self.g_repeat.set_sensitive(gtk.TRUE)
                self.g_repeat_arpeggio.set_sensitive(gtk.TRUE)
                self.g_new.set_sensitive(
                    not self.get_bool('config/picky_on_new_question'))
                self.clear_stacking_frame()
                self.g_stacking_frame.set_sensitive(gtk.FALSE)
                for c in self.g_chordtype_box.get_children():
                    c.set_sensitive(gtk.TRUE)
                self.m_t.play_question()
                self.g_flashbar.flash(_("Identify chord type"))
                self.g_chordtype_box.get_children()[0].grab_focus()
            elif g == Teacher.ERR_PICKY:
                self.g_flashbar.flash(_("You have to solve this question first."))
    def update_gui_after_lessonfile_change(self, *v):
        if self.m_t.m_P:
            self.g_new.set_sensitive(gtk.TRUE)
            self.fill_chordtype_box()
        else:
            self.g_new.set_sensitive(gtk.FALSE)
        self.g_repeat.set_sensitive(gtk.FALSE)
        self.g_repeat_arpeggio.set_sensitive(gtk.FALSE)
        self.g_give_up.set_sensitive(gtk.FALSE)
        self.g_win.set_title("Solfege - " + self.get_pretty_name())
    def clear_stacking_frame(self):
        for c in self.g_source.get_children() + self.g_answer.get_children():
            c.destroy()
    def fill_stacking_frame(self):
        """
        Create the buttons in stacking frame.
        """
        self.g_redo.set_sensitive(gtk.TRUE)
        self.g_stacking_frame.set_sensitive(gtk.TRUE)
        self.m_answer = []
        self.clear_stacking_frame()
        v = self.m_t.m_P.get_music().split()
        v.sort()
        for n in v:
            nn = mpd.MusicalPitch.new_from_notename(n)
            b = gtk.Button(nn.get_user_notename())
            b.connect('clicked', self.on_notebutton_clicked, nn.get_notename(), nn.get_user_notename())
            self.g_source.pack_end(b, gtk.FALSE, gtk.FALSE)
            b.show()
        self.g_source.get_children()[0].grab_focus()
    def give_up(self, v=None):
        self.m_t.give_up()
        self.g_give_up.set_sensitive(gtk.FALSE)
        self.g_new.set_sensitive(gtk.TRUE)
        self.g_new.grab_focus()
        self.set_chordtype_frame_status_solved(self.m_t.m_P.get_chordtype())
        self.clear_stacking_frame()
        self.g_stacking_frame.set_sensitive(gtk.TRUE)
        self.g_redo.set_sensitive(gtk.FALSE)
        self.show_music()
    def on_chordtype_clicked(self, btn, t):
        if self.m_t.q_status == const.QSTATUS_NO:
            self.g_flashbar.flash(_("Click 'New chord' to begin."))
        elif self.m_t.q_status in (const.QSTATUS_NEW, const.QSTATUS_TYPE_WRONG):
            g = self.m_t.guess_chordtype(t)
            if g:
                self.g_flashbar.flash(_("Correct, now stack the tones"))
                self.set_chordtype_frame_status_solved(t)
                self.fill_stacking_frame()
            else:
                self.g_flashbar.flash(_("Wrong"))
        elif self.m_t.q_status in (const.QSTATUS_TYPE_SOLVED, const.QSTATUS_VOICING_WRONG):
            self.g_flashbar.flash(_("Type is already solved, now specify voicing"))
    def on_notebutton_clicked(self, btn, n, user_notename):
        newb = gtk.Button(user_notename)
        newb.show()
        btn.destroy()
        self.m_answer.append(n)
        self.g_answer.pack_end(newb, gtk.FALSE, gtk.FALSE)
        if not self.g_source.get_children():
            # no children mean that the user has finished answering
            if self.m_t.guess_voicing(self.m_answer):
                self.g_flashbar.flash(_("Correct"))
                self.show_music()
                self.g_new.set_sensitive(gtk.TRUE)
                self.g_new.grab_focus()
                self.g_give_up.set_sensitive(gtk.FALSE)
                self.g_redo.set_sensitive(gtk.FALSE)
            else:
                self.g_flashbar.flash(_("Wrong"))
                self.g_redo.grab_focus()
        else:
            self.g_source.get_children()[0].grab_focus()
    def show_music(self):
        self.clear_stacking_frame()
        md = mpd.musicdisplayer.MusicDisplayer(None)
        self.g_source.pack_start(md)
        md.show()
        md.display(r"\staff{ \clef %s < %s >}" % (
                mpd.select_clef(self.m_t.m_P.get_music()),
                self.m_t.m_P.get_music()), 20)
        # display the notenames on the buttons with octave info
        for n in self.m_t.m_P.get_music().split():
            b = gtk.Button(mpd.MusicalPitch.new_from_notename(n).get_user_octave_notename())
            b.get_children()[0].set_use_markup(1)
            b.show()
            self.g_answer.pack_end(b, gtk.FALSE, gtk.FALSE)
    def fill_chordtype_box(self):
        for x in self.g_chordtype_box.get_children():
            x.destroy()
        if self.m_t.m_P:
            for t in self.m_t.m_P.m_chord_types.keys():
                b = gtk.Button(self.m_t.m_P.m_chord_types[t])
                b.set_data('chordtype', t)
                self.g_chordtype_box.pack_start(b, gtk.FALSE)
                b.connect('clicked', self.on_chordtype_clicked, t)
                b.show()
    def set_chordtype_frame_status_solved(self, t):
        for c in self.g_chordtype_box.get_children():
            c.set_sensitive(c.get_data('chordtype')==t)
    def on_start_practise(self):
        self.g_new.grab_focus()
        gtk.timeout_add(const.SHORT_WAIT, lambda self=self:
            self.g_flashbar.flash(_("Click 'New chord' to begin.")))
        self.fill_chordtype_box()
        self.clear_stacking_frame()
        self.g_stacking_frame.set_sensitive(gtk.FALSE)
    def on_end_practise(self):
        self.m_t.end_practise()
        self.g_new.set_sensitive(gtk.TRUE)
        self.g_repeat.set_sensitive(gtk.FALSE)
        self.g_repeat_arpeggio.set_sensitive(gtk.FALSE)
        self.g_give_up.set_sensitive(gtk.FALSE)
