#   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 *

MAX_LED = 16

class OBBTimer(QTimer):
    def __init__(self, interval):
        QTimer.__init__(self)
        self.connect(self, SIGNAL("timeout()"), self.timerbeat)

        self.bpm        = interval
        self.newBpm     = interval
        self.currentHit = 0
        self.duration   = 0

    def start(self, startHit = MAX_LED - 1, bpm = 0, beats = MAX_LED):
        self.currentHit = startHit
        self.duration = beats
        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(PYSIGNAL("hit(int)"), (self.currentHit,))
        if self.currentHit % 4 == (MAX_LED / 4) - 1 and self.newBpm != self.bpm:
            self.bpm = self.newBpm
            self.stop()
            self.start(self.currentHit)
            debug("changed bpm to %d" % self.bpm)
