package ch.epfl.isochrone.tiledmap;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;

import ch.epfl.isochrone.geo.PointOSM;
import ch.epfl.isochrone.timetable.FastestPathTree;
import ch.epfl.isochrone.timetable.Stop;

public final class IsochroneTileProvider implements TileProvider {
	private FastestPathTree arbreDesTrajets; 
	private ColorTable tableCouleur;
	private double vitesse; 

	public IsochroneTileProvider(FastestPathTree aDt, ColorTable tC, double v)
	{
		arbreDesTrajets = aDt; 
		tableCouleur = tC; 
		vitesse = v; 
	}

    @Override
    public Tile tileAt(int zoom, int x, int y) {
       
        double longueurPixelX = new PointOSM(zoom, x * 256, y * 256).toWGS84().distanceTo(new PointOSM(zoom, x * 256 + 1, y * 256).toWGS84());
        double longueurPixelY = new PointOSM(zoom, x * 256, y * 256).toWGS84().distanceTo(new PointOSM(zoom, x * 256, y * 256 + 1).toWGS84());
        
        BufferedImage image =
                new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();

        // Remplit avec un fond blanc
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, image.getWidth(), image.getHeight());

        
        for(int i=tableCouleur.nbTranche(); i>=1; i--)
        {
            for (Stop s : arbreDesTrajets.stops())
            {
                int t = tableCouleur.dureeTranche()*i - arbreDesTrajets.arrivalTime(s) + arbreDesTrajets.startingTime();
                if (t>0)
                {
                    double r1 = vitesse*t/longueurPixelX;
                    double r2 = vitesse*t/longueurPixelY;
                    
                    g.setColor(tableCouleur.couleurTranche(i));
                    g.fill(new Ellipse2D.Double(s.position().toOSM(zoom).x()-new PointOSM(zoom, x * 256, y * 256).x()-r1, s.position().toOSM(zoom).y()-new PointOSM(zoom, x * 256, y * 256).y()-r2, r1, r2));
                }
            }
        }
    	

        return new Tile(x, y, zoom, image);
    } 

}
