package org.lucci.madhoc.env.xy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.naming.ConfigurationException;

import org.lucci.io.stream.FileStreamSource;
import org.lucci.madhoc.env.MobilityModel;
import org.lucci.madhoc.network.net.Location;

public class XYMobility extends MobilityModel
{
    private List<Location> locations = new ArrayList<Location>();
    
    
    @Override
    public void moveStation(double duration, double simulatedTime)
    {
        int iteration = getMobileNode().getNetwork().getSimulation().getIteration();
        
        if (iteration < this.locations.size())
        {
            getMobileNode().setLocation(this.locations.get(iteration));
        }        
    }

    public void configure() throws Throwable
    {
        super.configure();
        String s = getMobileNode().getNetwork().getSimulation().getConfiguration().getString("xy_mobility_directory");
        s += File.separator + getMobileNode().getIdentifier() + ".txt";
        
        File file = new File(s);
        
        if (!file.exists())
        {
            throw new ConfigurationException("file " + file.getAbsolutePath() + " can't be found");            
        }
        else
        {
            FileStreamSource fss = new FileStreamSource(file);

            for (String line : fss.getLines())
            {
                int pos = line.indexOf(',');
                
                if (pos == -1)
                {
                    throw new ConfigurationException("in file " + file.getAbsolutePath() + ", line " + line + " is not of the 'x,y' form");            
                }
                else
                {
                    double x = Double.valueOf(line.substring(0, pos).trim());
                    double y = Double.valueOf(line.substring(pos + 1).trim());
                    Location p = new Location(x, y);
                    this.locations.add(p);
                }
            }
        }
    }
}