package utils;


public class Buffer {
    private Object [] contents;
    private boolean empty = true;
    private int max_len;
    private int read_pos = 0;
    private int write_pos = 0;
    private int remaining = 0;
    private boolean overflow = false;
    public Buffer(int max_len){
        this.max_len = max_len;
        contents = new Object[max_len];
    }
    
    public int getRemainingData(){
        return remaining;
    }
    public synchronized void put (Object p) throws InterruptedException {
        if(remaining >= max_len){
            overflow = true;
        }
        contents[write_pos] = p;
        write_pos++;
        if(write_pos >= max_len){
            write_pos = 0;
        }
        remaining++;
        empty = false;
        notify();
    }
    
    public synchronized Object get() throws InterruptedException{
        
        if(empty == true || remaining == 0)  {	
            return null;
        }
        int tmp = read_pos;
        deleteFirst();
        return contents[tmp];
        
    }
    
    private synchronized void deleteFirst(){
        synchronized (contents) {
            read_pos ++;
            if(read_pos >= max_len){
                read_pos = 0;
            }
            remaining--;
        }
    }
    
    
    
    public boolean isEmpty(){
        if(remaining == 0){
            return true;
        }
        return false;
    }
}