package modelling;

import java.awt.Image;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import sema.Agent;
import sema.Area;
import sema.Element;
import modelling.Selector;
import sema.Signal;
import sema.World;


/**
 * Agent able to detect and fallow pheromonae.
 */

public class PheromoneUserAgent extends Agent{
    
    /**
     * Creates a new user of pheromona.
     */
    public PheromoneUserAgent(World world, Area area, float delay, Image image, Image pheromoneImage) {
        super(world, area, delay, image);
        this.pheromoneImage = pheromoneImage;
    }
    
    
    Image pheromoneImage;
    
    /**
     * Secrets a pheromone at the place of the same place than the agent with the given contents and during.
     */
    public void letPheromone(String contents, float during, Selector selector){
        new Pheromone(world, new PonctualArea (world.map, getArea().getX(), getArea().getY(), 0.1f,0.1f, 0f), pheromoneImage, contents , during, selector);
    }
    
    /**
     * Returns the next pheromone "on the way" of the agent : determinates which of the "not too distant"
     * pheromones need the smallest change of radius to be reached.
     */
    private Element getNextPheromonae(String contents, float radius){
        TreeMap elements = world.nature.getElements(new CircularArea(world.map,getArea().getX(), getArea().getY(), radius, 0f));
        float nextAngle = 721;
        Element curentElement = null;
        Set cles = elements.keySet();
        Iterator iterator = cles.iterator();
        while (iterator.hasNext()) {
            Element ph = (Element) elements.get(iterator);
            if (ph.getKind().equals("pheromone")){
                Signal pheromone = (Signal) ph;
                double distance = world.nature.getDistance(ph,this);
                float angle = Math.abs(this.getArea().getX() - (float)Math.atan2(ph.getArea().getY()-getArea().getY(),ph.getArea().getX()-getArea().getX()));
                if ((angle < nextAngle)&&(distance <= (double) 0.1) && contents.equals(pheromone.getContents())){
                    curentElement = ph;
                    nextAngle = angle;
                }
            }
        }
        return curentElement;
    }
    
}
