// License: GPL. See LICENSE file for details.
package org.openstreetmap.josm.gui.download;

import static org.openstreetmap.josm.tools.I18n.tr;

import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.IOException;
import java.util.logging.Logger;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.openstreetmap.josm.data.Bounds;
import org.openstreetmap.josm.tools.GBC;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
 * ID Number Selector
 * 
 * Input method for the "Download from OSM" dialog box.  Given an OSM element ID number,
 * it finds the center point and loads small additional area on each side.
 * Very handy if you've found a problem element in an XML or database dump.
 * 
 * Example: enter node id 1, to see the first node ever added to OSM
 * TODO: support ways/relations
 *
 * @author Bryce Nesbitt, April 2011
 *
 */
public class IdNumberSelection implements DownloadSelection {
	private static final Logger logger = Logger.getLogger(IdNumberSelection.class.getName());

    private DownloadDialog parent;
    private JTextField osmid = new JTextField(11);
    private int lastid = 0;

    public void addGui(final DownloadDialog gui) {
    	BoundingBoxBuilder bboxbuilder = new BoundingBoxBuilder();
    	osmid.addFocusListener (bboxbuilder);
    	osmid.addActionListener(bboxbuilder);
    	
        final JPanel dlg = new JPanel(new GridBagLayout());
        dlg.add(new JLabel(tr("OSM Node ID")), GBC.std().insets(10,20,5,0));
        dlg.add(osmid, GBC.std().insets(0,20,0,0));
        gui.addDownloadAreaSelector(dlg, tr("Node ID"));
        parent = gui;
    }

    public void setDownloadArea(Bounds area) {
    }
    
    class BoundingBoxBuilder extends FocusAdapter implements ActionListener {
 
    	protected void refreshBounds() {
            double fudgelon=.001, fudgelat=.001;
            double mylon=0,       mylat=0;
            
            // Extract the OSM element ID the user wants as the center point
            int id;
			try {
				id = Integer.parseInt(osmid.getText().trim());
			} catch (NumberFormatException e1) {
	            Bounds b = new Bounds(0,0,0,0);
	            parent.boundingBoxChanged(b, IdNumberSelection.this);
	            return;
			}
            if( id == lastid ) {
            	return;
            }
            lastid = id;            
			
			// Use the DOM to load an element from the API, and parse out the lat/lon.
			String url = "http://api.openstreetmap.org/api/0.6/node/"+id;
			try {
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				logger.info(url);
				Document doc = db.parse(url);				
				Node         node = doc.getElementsByTagName("node").item(0);
				NamedNodeMap nmap = node.getAttributes();
				mylat = Double.parseDouble(nmap.getNamedItem("lat").getNodeValue());
				mylon = Double.parseDouble(nmap.getNamedItem("lon").getNodeValue());					
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				mylat = mylon = 0;
			}	
						
            Bounds b = new Bounds(mylat-fudgelon,mylon-fudgelat,mylat+fudgelon,mylon+fudgelat);
            parent.boundingBoxChanged(b, IdNumberSelection.this);
        }
        public void focusLost(FocusEvent e) {
            refreshBounds();
        }
        public void actionPerformed(ActionEvent e) {
            refreshBounds();
        }
    }
}