package com.imsl.demo.jsp;
import com.imsl.chart.*;
import com.imsl.chart.xml.ChartXML;
import org.xml.sax.InputSource;
import java.io.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.servlet.http.*;

public class XmlBean extends JspBean {
    static private java.util.Hashtable hashSource = new java.util.Hashtable();
    
    private JspBean bean;
    private String  xml = "";
    
    public XmlBean() {
        bean = new JspBean();
        bean.setSize(400,400);
        bean.setCreateImageMap(true);
    }        
    
    public void setXML(String xml) {
        this.xml = xml.trim();
    }
    
    /**
     *  Set XML from a data file loaded as a resource.
     *  @param src is the name of the data set to be loaded.
     *      The data must be a resource in the base package
     *      with name src+".xml".
     */
    public void setSource(String src) {
        if (xml != null  &&  xml.length() > 0)  return;
        String sample = (String)hashSource.get(src);
        if (sample != null) {
            xml = sample;
            return;
        }
        try {
            InputStream is = getClass().getResourceAsStream(src+".xml");
            if (is == null)  return;
            StringBuffer sb = new StringBuffer(1000);
            char buf[] = new char[512];
            Reader reader = new InputStreamReader(is);
            while (true) {
                int n = reader.read(buf);
                if (n < 0)  break;
                sb.append(buf, 0, n);
            }
            is.close();
            xml = sb.toString();
            hashSource.put(src, xml);
        } catch (IOException e) {
            e.printStackTrace();
        }        
    }
    
    public void createChart(HttpServletRequest request)
             throws SAXException, IOException, ParserConfigurationException{
        if (xml.length() == 0)  return;
        InputSource is = new InputSource(new java.io.StringReader(this.xml));
        ChartXML chartXML = new ChartXML(is, false);
        bean.registerChart(chartXML.getChart(), request);
    }
    
    public String getXML() {
        return xml;
    }
    
    public String getImageTag() {
        return bean.getImageTag();
    }
    
    public String getImageMap() {
        return bean.getImageMap();
    }
}