/*************************************************************************
 * PCRaw
 * Author: nori090
 * Original author: ◆e5bW6vDOJ.
 * Copyright: Copyright (C) 2008 nori090
 * Copyright: Copyright (C) 2007 ◆e5bW6vDOJ.
 * Date: February 11, 2007
 * License: 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 * 
 * http://mosax.sakura.ne.jp/fswiki.cgi?page=PCRaw
 */
package org.coderepos.nori090.pcraw;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author nori090
 * @version $Rev: 137 $ $Date: 2008-08-01 06:27:55 +0900 (Fri, 01 Aug 2008) $
 */
public class KeyManager {
    private static final Log log = LogFactory.getLog( KeyManager.class );

    ArrayList<Key> keys;

    int beforeKey;

    long lifeTime;

    public KeyManager() {
        super();
        clear();
    }

    void clear() {
        keys = new ArrayList<Key>();
        lifeTime = 0;
        beforeKey = -1;
    }

    void swap( int i, int j ) {
        if ( i == j )
            return;
        log.debug( String.format( "鍵を交換. Key No.%d ⇔ Key No.%d", i, j ) );
        Collections.swap( keys, i, j );
    }

    int add( byte[] key, long t ) {
        if ( t == 0L ) {
            t = PCRawTools.time();
        }
        for ( int i = 0; i < keys.size(); i++ ) {
            if ( Arrays.equals( key, keys.get( i ).key ) ) {
                log.debug( "鍵を更新. Key No." + i );
                keys.get( i ).t = t;
                return i;
            }
        }
        log.debug( "鍵を追加." );
        Key k = new Key();
        k.key = key;
        k.t = t;
        keys.add( k );
        return keys.size() - 1;
    }

    int deleteOld() {
        long t = PCRawTools.time();
        ArrayList<Key> list = new ArrayList<Key>();
        for ( Key k : keys ) {
            if ( t - k.t <= lifeTime ) {
                list.add( k );
            }
        }
        keys = list;
        log.debug( "生存中の鍵: " + list.size() );
        return list.size();
    }

    int count() {
        return keys.size();
    }

    static class Key {
        public byte[] key;

        long t;
    }
}
