/*
 *  Agent's input buffer module
 *
 *  2004 - 2011 Frantisek Zboril jr.
 *  Faculty of Information Technology
 *  zborilf@fit.vutbr.cz
 *  http://www.fit.vutbr.cz/~zborilf
 *
 * (C) Brno University of Technology
 * Freeware licence VUT v Brně
 * https://wis.fit.vutbr.cz/FIT/db/dir.php/dr/VZ2007/externiInformace/softwareNaWebu/Priloha2_rozh23.pdf

 */

package jTMass.core.jAMass;
import jTMass.TMass;
import jTMass.core.jALLL.jTObjects.*;


public class TInputBuffer{
	
    private TStorageBox PDatabase=new TStorageBox();

    // ===== BUFFER CLONING =====

    protected TStorageBox getDatabaseClone(){
	return((TStorageBox)PDatabase.clone());
    }

    // ===== TERMINAL =====
    
    public void printInputBuffer(){
	PDatabase.printBox(false);
    }

    // ===== READERS, WRITERS =====

    public int getSize(){
        return(PDatabase.getSize());
    }

    protected void setDatabase(TStorageBox database){
	PDatabase=database;
    }

    public String getContent(){
        return(PDatabase.getBeliefs());
    }

    // ===== INPUT BUFFER ACCESS =====

    public boolean receiveMessage(String agent, TList message){

        TList list=new TList();
		
        TMass._Terminal.printlnDebug(agent+"Message received from: "+agent+"");
	list.add(new TAtom(agent));
	list.add(message);
	PDatabase.put(list);
	return(true);
    }
	
    public TObject getMessage(){
	TList query=new TList(TConstants._QueryList);
	TObject result;

        query.add(new TAtom(TConstants._AnonymousVariable)); //sender
        query.add(new TAtom(TConstants._AnonymousVariable)); //message
        TStorageBuffer buffer=PDatabase.unify(query);
        result=(TList)buffer.next();
        if(result!=null){
            // remove the message from the input buffer
            PDatabase.remove(result.getContent());
            return(result);
        }
        return(new TFail());
    }
	
    public TObject getMessageFrom(String agent){
        TList query=new TList(TConstants._QueryList);
        TObject result;

        query.add(new TAtom(agent));
        query.add(new TAtom(TConstants._AnonymousVariable));
        TStorageBuffer buffer=PDatabase.unify(query);
        result=(TList)buffer.next();
        if (result!=null)
            PDatabase.remove(result.getContent());
        else
            result=new TFail();
        return(result);
    }
	
    public void clearBuffer(){
        PDatabase.clear();
    }

     // ===== CONSTRUCTORS =====

    public TInputBuffer() {
        PDatabase=new TStorageBox();
    }
	
    public TInputBuffer(int initialCapacity){
        PDatabase=new TStorageBox(initialCapacity);
    }
	
    public TInputBuffer(int initialCapacity, float loadFactor){
        PDatabase=new TStorageBox(initialCapacity, loadFactor);
    }

}