/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package usda.weru.weps.location;



import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.SwingWorker;
import org.apache.log4j.Logger;
import org.jscience.geography.coordinates.LatLong;
import usda.weru.gis.GISData;
import usda.weru.gis.GISLookup;
import usda.weru.util.FireAllContext;
import usda.weru.util.LoadingContext;
import usda.weru.util.PropertyStackContext;
import usda.weru.weps.RunFileBean;

/**
 *
 * @author Joseph Levin <joelevin@weru.ksu.edu>
 */
public class LatLongSiteController implements PropertyChangeListener {

    
    private static final Logger LOGGER = Logger.getLogger(LatLongSiteController.class);
    private final RunFileBean c_bean;

    private LatLongSiteController(RunFileBean bean) {
        c_bean = bean;
        c_bean.addPropertyChangeListener(RunFileBean.PROP_SITE, this);
        c_bean.addPropertyChangeListener(RunFileBean.PROP_LATLONG, this);
    }

    public static final void install(RunFileBean bean) {
        new LatLongSiteController(bean);
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        assert evt.getSource() == c_bean;

        if (LoadingContext.isLoading(true) || FireAllContext.isInFireAll(true)) {
            return;
        }

        if (RunFileBean.PROP_SITE.equals(evt.getPropertyName())) {
            siteChanged(c_bean.getSite());
        } else if (RunFileBean.PROP_LATLONG.equals(evt.getPropertyName())) {
            latlongChanged(c_bean.getLatLong());
        }
    }

    private void latlongChanged(final LatLong latlong) {

        if (PropertyStackContext.isPropertyOnStack(c_bean, RunFileBean.PROP_SITE, false)) {
            return;
        }
        try {
            GISLookup<Site> lookup = GISData.getInstance().getLookup(Site.class);
            List<Site> results = lookup.lookup(latlong);

            if (results.size() > 0) {
                Comparator<Site> c = new Site.HierarchyComparator();
                Collections.sort(results, c);
                Site mostDetail = results.get(results.size() - 1);
                c_bean.setSite(mostDetail);
            } else {
                c_bean.setSite(null);
            }

        } catch (Exception e) {
            //log the error
            e.printStackTrace();
        }


    }

    private void siteChanged(final Site site) {

        if(site == null){
            return;
        }

       if (PropertyStackContext.isPropertyOnStack(c_bean, RunFileBean.PROP_LATLONG, false)) {
            return;
        }

//        SwingWorker<LatLong, Void> worker = new SwingWorker<LatLong, Void>() {
//
//            @Override
//            protected LatLong doInBackground() throws Exception {
//                    if(site == null){
//                        return null;
//                    }
//                    LatLong latlong = site.getLatLong();
//                    if (latlong != null) {
//                        LOGGER.debug("Found latlong for site: " + site);
//                        return latlong;
//                    } else {
//                        LOGGER.debug("Unable to determine latlong for site: " + site + ".");
//                        return null;
//                    }
//            }
//
//            @Override
//            protected void done() {
//                //this is executed on the event queue
//                try{
//                    c_bean.setLatLong(get());
//                }
//                catch(Exception e){
//                    LOGGER.error("Unable to find a latlong.  GIS query has possibly timed out.", e);
//                }
//                finally{
//                    PropertyStackContext.exit(c_bean, RunFileBean.PROP_SITE);
//                }
//
//            }
//
//
//
//        };
//        if(EventQueue.isDispatchThread()){
//            PropertyStackContext.enter(c_bean, RunFileBean.PROP_SITE);
//        }
//        else{
//            try{
//                EventQueue.invokeAndWait(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        PropertyStackContext.enter(c_bean, RunFileBean.PROP_SITE);
//                    }
//                });
//            }
//            catch(Exception e){
//                LOGGER.error("Unable to enter property stack.", e);
//            }
//        }
        
        
        c_bean.setLatLong(site.getLatLong());

        
        //worker.execute();





    }
}
