/*
 * Copyright 2009-2013 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.sh.misc;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

public class RingBuffer<E> implements java.io.Serializable {

	//
	private static final long serialVersionUID = 5015372387740172285L;

	//
	private Object[] buffer;
	private int ptrt;
	private int ptrb;

	/**
	 * 
	 * @param size
	 */
	public RingBuffer(int size) {
		buffer = new Object[size];
		ptrt = 0;
		ptrb = -1;
	}

	private void incb() {
		ptrb = ptrb < buffer.length ? ptrb + 1 : 1;
	}

	private void inct() {
		ptrt = ptrt < buffer.length ? ptrt + 1 : 1;
	}

	private void dect() {
		ptrt = ptrt > 0 ? ptrt - 1 : buffer.length - 1;
	}

	private int index(int c) {
		return (ptrb + c) % buffer.length;
	}

	/**
	 * 
	 * @param c
	 * @return
	 */
	public boolean add(Object c) {
		if(ptrb < 0) {
			ptrb = 0;
		} else if(ptrt % buffer.length == ptrb % buffer.length) {
			incb();
		}
		buffer[ptrt < buffer.length ? ptrt : 0] = c;
		inct();
		return size() < buffer.length;
	}

	/**
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public E remove() {
		E res;

		if(ptrb < 0)  throw new NoSuchElementException();
		dect();
		res = (E)buffer[ptrt];
		if(ptrb == ptrt)  ptrb = -1;
		return res;
	}

	/**
	 * 
	 * @return
	 */
	public int size() {
		if(ptrb < 0)  return 0;
		return ptrt <= ptrb ?
				ptrt + buffer.length - ptrb : ptrt - ptrb;
	}

	/**
	 * 
	 * @param c
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public E get(int c) {
		if(c >= buffer.length) {
			throw new IndexOutOfBoundsException("" + c);
		} else if(c >= size()) {
			throw new NoSuchElementException();
		}
		return (E)buffer[index(c)];
	}

	/**
	 * 
	 * @return
	 */
	public boolean isEmpty() {
		return ptrb < 0;
	}

	/**
	 * 
	 */
	public void clear() {
		ptrt = 0;
		ptrb = -1;
	}

	/**
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<E> toList() {
		List<E> l = new ArrayList<E>();
		int e;

		e = ptrb < ptrt ? ptrt : ptrt + buffer.length;
		for(int i = ptrb; i < e; i++) {
			l.add((E)buffer[i % buffer.length]);
		}
		return l;
	}

}
