from sugar.activity import activity

from Csound import *
from CsoundServer import *

import random
import gtk

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

gisin	ftgen	1, 0, 4096, 10, 1

    instr	10
iPitch	= 	cpspch(p4)

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

    outs	a1, a1
    endin
    """

    def destroy(self, data=None):    
        if self.server.didLaunch():
            self.csound.shutdownServer()
            
        activity.Activity.destroy(self)

    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.server = CsoundServer(activity.get_bundle_path(), 'csoundserver')
        fd = self.server.launch()
        if fd != None:
            gobject.io_add_watch(fd.fileno(), gobject.IO_IN, self.serverMessages, fd)        
        
        self.set_title('Hello Csound')

        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()

        self.button = gtk.Button("Click Me")
        self.button.set_size_request(75, 25)
        
        self.button.connect("clicked", self.hello, None)
    
        self.set_canvas(self.button)
    
        self.button.show()
    
        self.csound = Csound("Button Example")
        self.csound.setMessageCallback(self.csoundMessages)
        self.csound.setupOrchestraAsString(self.orchestra)
        self.csound.initialize()
        self.csound.perform()

    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 serverMessages(self, source, condition, userData = None):
        # here, userData is the file descriptor
        print userData.readline(),
        # return True to keep processing
        return True

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