#   Copyright (C) 2003 Yannick Gingras <ygingras@ygingras.net>
#   Copyright (C) 2003 Vincent Barbin <vbarbin@openbeatbox.org>

#   This file is part of Open Beat Box.

#   Open Beat Box 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.

#   Open Beat Box 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 Open Beat Box; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from os import *
from OBBCSoundTorturer import *
from OBBFuncts import *

class OBBInstrument:
    def __init__(self, filePath, volume = 100, pan = 0, reverb = 0):
        self.filePath = filePath
        self.playFilePath = filePath
        self.panning = pan
        self.reverb = reverb
        self.setVolume(volume)
        self.setDuration()

    def deleteTempSampleFile(self):
        debug("Instrument deleted")
        if self.getFilePath() != self.getPlayFilePath():
            if access(self.getPlayFilePath(), R_OK):
                remove(self.getPlayFilePath())

    def setFilePath(self, filePath):
        self.filePath = filePath
        self.refreshSample()
        
    def getFilePath(self):
        return self.filePath

    def setPanning(self, pan):
        self.panning = pan
        self.leftVolume = 1.0*(100-self.panning)/100*self.volume
        self.rightVolume = 1.0*(100+self.panning)/100*self.volume
        if self.leftVolume > self.volume:
            self.leftVolume = self.volume
        if self.rightVolume > self.volume:
            self.rightVolume = self.volume
        self.refreshSample()

    def setVolume(self, volume):
        self.volume = volume
        self.setPanning(self.panning)

    def getVolume(self):
        return self.volume

    def setPlayFilePath(self, filePath):
        self.playFilePath = filePath

    def getPlayFilePath(self):
        return self.playFilePath

    def setDuration(self, duration = None):
        if duration == None:
            wavefile = open(self.playFilePath, 'r')
            self.duration = (1.0 * wavefile.getnframes()) \
                    /(1.0 * wavefile.getframerate())
            wavefile.close()
        else:
            self.duration = 1.0 * duration

    def refreshSample(self):
        if self.getFilePath() != self.getPlayFilePath():
            if access(self.getPlayFilePath(), R_OK):
                remove(self.getPlayFilePath())
        self.setPlayFilePath(OBBCSoundTorturer().createModifiedSampleFile(self))
        self.setDuration()
