/*
 * VsqEventList.java
 * Copyright (c) 2008 kbinani
 *
 * This file is part of jp.sourceforge.lipsync.vsq.
 *
 * jp.sourceforge.lipsync.vsq is free software; you can redistribute it and/or
 * modify it under the terms of the BSD License.
 *
 * jp.sourceforge.lipsync.vsq 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.
 */
package jp.sourceforge.lipsync.vsq;

import java.util.*;

/// <summary>
/// 固有ID付きのVsqEventのリストを取り扱う
/// </summary>
public class VsqEventList {
    private Vector<VsqEvent> m_list;
    private Vector<Integer> m_ids;

    /// <summary>
    /// コンストラクタ
    /// </summary>
    public VsqEventList() {
        m_list = new Vector<VsqEvent>();
        m_ids = new Vector<Integer>();
    }

    public VsqEventIterator iterator( VsqEventIteratorMode mode ) {
        return new VsqEventIterator( m_list, mode );
    }
    
    public VsqEventIterator iterator(){
        return iterator( VsqEventIteratorMode.All );
    }

    public void add( VsqEvent item ) {
        int new_id = GetNextId( 0 );
        item.InternalID = new_id;
        m_list.add( item );
        m_ids.add( new_id );
        boolean changed = true;
        while ( changed ) {
            changed = false;
            for ( int i = 0; i < m_list.size() - 1; i++ ) {
                if ( m_list.get( i ).compareTo( m_list.get( i + 1 ) ) > 0 ) {
                    VsqEvent t = (VsqEvent)m_list.get( i ).clone();
                    m_list.set( i, m_list.get( i + 1 ) );
                    m_list.set( i + 1, t );
                    changed = true;
                }
            }
        }
        for ( int i = 0; i < m_list.size(); i++ ) {
            m_ids.set( i, m_list.get( i ).InternalID );
        }
    }

    public void removeAt( int index ) {
        m_list.remove( index );
        m_ids.remove( index );
    }

    private int GetNextId( int next ) {
        int index = -1;
        Vector<Integer> current = new Vector<Integer>( m_ids );
        int nfound = 0;
        while ( true ) {
            index++;
            if ( !current.contains( index ) ) {
                nfound++;
                if ( nfound == next + 1 ) {
                    return index;
                } else {
                    current.add( index );
                }
            }
        }
    }

    public int size() {
        return m_list.size();
    }

    public VsqEvent get( int index ) {
        return m_list.get( index );
    }

    public void set( int index, VsqEvent value ) {
        m_list.add( index, value );
    }

}
