package ch.epfl.isochrone.gui;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JViewport;

import ch.epfl.isochrone.geo.PointOSM;
import ch.epfl.isochrone.tiledmap.IsochroneTileProvider;
import ch.epfl.isochrone.tiledmap.Tile;
import ch.epfl.isochrone.tiledmap.TileProvider;

public final class TiledMapComponent extends JComponent {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    public int zoom; 
    private List<TileProvider> listeFournisseur;
    public PointOSM position;  // point en haut à gauche
    public JViewport view;
    
    public TiledMapComponent(int zoom)
    {
        super();
        
        if(zoom < 10 || zoom > 19){
            throw new IllegalArgumentException();
        }
        
        this.zoom = zoom; 
        listeFournisseur = new ArrayList<TileProvider>();
    }
    
    public int zoom(){
        return zoom;
    }
    
    public void setZoom(int zoom){
        if(zoom < 10 || zoom > 19){
            throw new IllegalArgumentException();
        }
        
        this.zoom = zoom;
        
    }
    
    public void setPosition(PointOSM position){
        this.position=position;
    }
    
    public void addTileProvider(TileProvider tp)
    {
        listeFournisseur.add(tp);    
    }
    
    public Dimension getPreferredSize()
    { 
        return new Dimension((int)Math.pow(2, zoom+8),(int)Math.pow(2, zoom+8));
    }
    
    public void paintComponent(Graphics g0)
    {
       Graphics2D g1 = (Graphics2D)g0; 
       Rectangle rect = getVisibleRect();
       
       for (int i=0; i<rect.width/256 + 2; i++)
       {
           for (int j=0; j<rect.height/256 + 2; j++)
           {
               for (int k=0; k<listeFournisseur.size(); k++)
               {
                   g1.drawImage(listeFournisseur.get(k).tileAt(zoom, (int)(rect.x/256)+i, (int)(rect.y/256)+j).image(), null, rect.x+i*256-rect.x%256, rect.y+j*256-rect.y%256);
               }
           }
       }
       
    }
    
    
    
    
}
