#   Copyright (C) 2002-2003 Yannick Gingras <ygingras@ygingras.net>
#   Copyright (C) 2002-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 OBBFuncts import *
from qt import *

import OBBSignals

class OBBTimer(QTimer):
    def __init__(self, interval, duration = 16):
        QTimer.__init__(self)
        self.connect(self, SIGNAL("timeout()"), self.timerbeat)
        self.refreshRate = 4
        self.bpm = interval
        self.newBpm = interval
        self.currentHit = 0
        self.duration = duration

    def start(self, startHit = 15, bpm = 0):
        self.currentHit = startHit
        if bpm:
            QTimer.start(self, 60000/bpm)
        else:
            QTimer.start(self, 60000/self.bpm)

    def stop(self):
        QTimer.stop(self)

    def changeBpm(self, bpm):
        if not self.isActive():
            self.bpm = bpm
            debug("changed bpm to %d" % self.bpm)
        self.newBpm = bpm

    def getInterval(self):
        return self.bpm

    def timerbeat(self):
        self.currentHit += 1
        self.currentHit %= self.duration
        self.emit(OBBSignals.hitPlayed, (self.currentHit,))
        if self.newBpm != self.bpm\
        and self.currentHit % self.refreshRate == 0:
            self.bpm = self.newBpm
            self.changeInterval(60000/self.newBpm)
            debug("changed bpm to %d" % self.bpm)
