from sugar.activity import activity
import logging

from Csound import *
from CsoundServer import *

import random
import sys, os
import gtk

import gobject

class HelloCsoundActivity(activity.Activity):
    orchestra = """
    nchnls = 2

gisin	ftgen	1, 0, 4096, 10, 1, 0.5, 0.25, 0.125

    instr	10
iPitch	= 	cpspch(p4)

aAmp    line    ampdbfs(-6), p3, 0
a1      oscil	aAmp, iPitch, gisin

    outs	a1, a1
    endin
    """

    def destroy(self, data=None):
        print "Destroy"
        self.csound.shutdownServer()
        return True

    def __init__(self, handle):
        print "running activity init", handle
        activity.Activity.__init__(self, handle)

        print "Launch Server"

        server = CsoundServer()
        fd = server.launch(msgs=0)
        #if fd != None:
        #    gobject.io_add_watch(fd.fileno(), gobject.IO_IN, self.serverMessages, fd)
                 
        print "Server Done"
                
        self.connect('destroy', self.destroy)
        
        self.set_title('Hello World')

        # Creates the Toolbox. It contains the Activity Toolbar, which is the
        # bar that appears on every Sugar window and contains essential
        # functionalities, such as the 'Collaborate' and 'Close' buttons.
        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()

        # Creates a new button with the label "Hello World".
        self.button = gtk.Button("Click Me")
        self.button.set_size_request(75, 25)
        
        # When the button receives the "clicked" signal, it will call the
        # function hello() passing it None as its argument.  The hello()
        # function is defined above.
        self.button.connect("clicked", self.hello, None)
    
        # Set the button to be our canvas. The canvas is the main section of
        # every Sugar Window. It fills all the area below the toolbox.
        self.set_canvas(self.button)
    
        # The final step is to display this newly created widget.
        self.button.show()
    
        # Create our instance        
        self.csound = Csound("Button Example")
        self.csound.setMessageCallback(self.csoundMessages)
        self.csound.setupOrchestraAsString(self.orchestra)
        self.csound.initialize()
        self.csound.perform()


    def serverMessages(self, source, condition, userData = None):
        print userData.readline(),
        return True

    def hello(self, widget, data=None):
        instrument = 10
        start = 0
        duration = 1
        scaleDegree = random.randint(0, 11) / 100.0
        octave = 8.00
        pitch = octave + scaleDegree
        
        self.csound.playEvent('i', [instrument, start, duration, pitch])

    def csoundMessages(self, message):
        message.display("Csound")
        pass
