package com.digero.common.view;

import javax.swing.JLabel;

import com.digero.common.midi.IBarNumberCache;
import com.digero.common.midi.SequencerEvent;
import com.digero.common.midi.SequencerListener;
import com.digero.common.midi.SequencerProperty;
import com.digero.common.midi.SequencerWrapper;
import com.digero.common.util.IDiscardable;

public class BarNumberLabel extends JLabel implements SequencerListener, IDiscardable
{
	private IBarNumberCache barNumberCache;
	private SequencerWrapper sequencer;
	private long initialOffsetTick = 0;

	public BarNumberLabel(SequencerWrapper sequencer, IBarNumberCache barNumberCache)
	{
		this.sequencer = sequencer;
		this.barNumberCache = barNumberCache;

		sequencer.addChangeListener(this);
	}

	@Override public void discard()
	{
		if (sequencer != null)
			sequencer.removeChangeListener(this);
	}

	public IBarNumberCache getBarNumberCache()
	{
		return barNumberCache;
	}

	public void setBarNumberCache(IBarNumberCache barNumberCache)
	{
		if (this.barNumberCache != barNumberCache)
		{
			this.barNumberCache = barNumberCache;
			update();
		}
	}

	public long getInitialOffsetTick()
	{
		return initialOffsetTick;
	}

	public void setInitialOffsetTick(long initialOffsetTick)
	{
		if (this.initialOffsetTick != initialOffsetTick)
		{
			this.initialOffsetTick = initialOffsetTick;
			update();
		}
	}

	@Override public void propertyChanged(SequencerEvent evt)
	{
		SequencerProperty p = evt.getProperty();
		if (p.isInMask(SequencerProperty.THUMB_POSITION_MASK | SequencerProperty.LENGTH.mask
				| SequencerProperty.TEMPO.mask | SequencerProperty.SEQUENCE.mask))
		{
			update();
		}
	}

	private int lastPrintedBarNumber = -1;
	private int lastPrintedBarCount = -1;

	private void update()
	{
		if (barNumberCache == null)
		{
			if (lastPrintedBarNumber != -1 || lastPrintedBarCount != -1)
			{
				lastPrintedBarNumber = -1;
				lastPrintedBarCount = -1;
				setText("");
			}
			return;
		}

		long tickLength = Math.max(0, sequencer.getTickLength() - initialOffsetTick);
		long tick = Math.min(tickLength, Math.max(0, sequencer.getThumbTick() - initialOffsetTick));

		int barNumber = barNumberCache.tickToBarNumber(tick) + 1;
		int barCount = barNumberCache.tickToBarNumber(tickLength) + 1;

		if (barNumber != lastPrintedBarNumber || barCount != lastPrintedBarCount)
		{
			lastPrintedBarNumber = barNumber;
			lastPrintedBarCount = barCount;
			setText(barNumber + "/" + barCount);
		}
	}
}

@@ -2150,28 +2150,16 @@
 kLength,
- Math.max(0,
  sequenc
@@ -2196,17 +2196,16 @@
 setTick)
-)
 ;%0D%0A%0D%0A%09%09i
@@ -2211,32 +2211,50 @@
 int barNumber = 
+(tick %3C 0) ? 0 : (
 barNumberCache.t
@@ -2277,16 +2277,17 @@
 ick) + 1
+)
 ;%0D%0A%09%09int

Tweak BarNumberLabel