package net.sf.jasperreports.charts.util;

import java.util.Map;
import net.sf.jasperreports.engine.JRPrintHyperlink;
import net.sf.jasperreports.engine.util.Pair;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.XYItemEntity;
import org.jfree.data.xy.XYDataset;

public class XYChartHyperlinkProvider implements ChartHyperlinkProvider {
  private static final long serialVersionUID = 10200L;
  
  private Map itemHyperlinks;
  
  public XYChartHyperlinkProvider(Map itemHyperlinks) {
    this.itemHyperlinks = itemHyperlinks;
  }
  
  public JRPrintHyperlink getEntityHyperlink(ChartEntity entity) {
    JRPrintHyperlink printHyperlink = null;
    if (hasHyperlinks() && entity instanceof XYItemEntity) {
      XYItemEntity itemEntity = (XYItemEntity)entity;
      XYDataset dataset = itemEntity.getDataset();
      Comparable serie = dataset.getSeriesKey(itemEntity.getSeriesIndex());
      Map serieHyperlinks = (Map)this.itemHyperlinks.get(serie);
      if (serieHyperlinks != null) {
        Number x = dataset.getX(itemEntity.getSeriesIndex(), itemEntity.getItem());
        Number y = dataset.getY(itemEntity.getSeriesIndex(), itemEntity.getItem());
        Object xyKey = new Pair(x, y);
        printHyperlink = (JRPrintHyperlink)serieHyperlinks.get(xyKey);
      } 
    } 
    return printHyperlink;
  }
  
  public boolean hasHyperlinks() {
    return (this.itemHyperlinks != null && this.itemHyperlinks.size() > 0);
  }
}
