package edu.sc.seis.gee.task;

import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import org.apache.log4j.Logger;
import org.omg.CORBA_2_3.ORB;
import edu.sc.seis.fissuresUtil.netConnChecker.ConnChecker;
import edu.sc.seis.fissuresUtil.netConnChecker.ConnStatus;
import edu.sc.seis.fissuresUtil.netConnChecker.ConnStatusChangedListener;
import edu.sc.seis.fissuresUtil.netConnChecker.ConnStatusResult;
import edu.sc.seis.fissuresUtil.netConnChecker.CorbaChecker;
import edu.sc.seis.fissuresUtil.netConnChecker.HTTPChecker;
import edu.sc.seis.fissuresUtil.netConnChecker.StatusChangedEvent;
import edu.sc.seis.gee.CommonAccess;
import edu.sc.seis.gee.configurator.ConfigurationException;
/**
 * ConnectionStatusTask.java
 *
 *
 * Created: Mon Jan 28 14:23:46 2002
 *
 * @author <a href="mailto:">Srinivasa Telukutla</a>
 * @version
 */

public class ConnectionStatusTask extends JPanel implements Task, ConnStatusChangedListener {
    public ConnectionStatusTask () {
        String imageFilename= "green.gif";
        String defaultsFilename= "edu/sc/seis/gee/data/images/";
        String fileName = defaultsFilename + imageFilename;
        green = new ImageIcon((ConnectionStatusTask.class).getClassLoader().getResource(fileName));
        fileName = defaultsFilename + "yellow.gif";
        yellow =  new ImageIcon((ConnectionStatusTask.class).getClassLoader().getResource(fileName));
        fileName = defaultsFilename + "red.gif";
        red =  new ImageIcon((ConnectionStatusTask.class).getClassLoader().getResource(fileName));
        fileName = defaultsFilename + "blue.gif";
        blue =  new ImageIcon((ConnectionStatusTask.class).getClassLoader().getResource(fileName));
    }
    
    public void statusChanged(StatusChangedEvent e) { updateStatus(); }
    
    public void configure(Map params) throws ConfigurationException{
        this.params = params;
        this.setLayout(grid);
    }
    
    private void buildCheckers() throws ConfigurationException {
        if(!built){
            Iterator it = params.keySet().iterator();
            while(it.hasNext()) {
                ConnChecker config = null;
                String cur = (String) it.next();
                if(params.get(cur) instanceof String){
                    String url = (String)params.get(cur);
                    if(url.startsWith("http")) {
                        config = new HTTPChecker(cur, url);
                    } else if(url.startsWith("corbaloc")) {
                        ORB orb = CommonAccess.getCommonAccess().getORB();
                        org.omg.CORBA.Object rootObj = orb.string_to_object(url);
                        config = new CorbaChecker(rootObj, cur);
                    }
                }
                if(config != null) {
                    config.addConnStatusChangedListener(this);
                    CommonAccess.getCommonAccess().add(config);
                }
            }
            built = true;
        }
    }
    
    public void invoke() throws ConfigurationException{ 
        buildCheckers();
        updateStatus();
    }
    
    public void destroy(){}
    
    private void updateStatus() {
        CommonAccess ca = CommonAccess.getCommonAccess();
        ConnChecker[] connCheckers = ca.getChecker().getCheckers();
        boolean newChecker = false;
        for (int i = 0; i < connCheckers.length; i++) {
            ConnStatusResult status = connCheckers[i].getStatus();
            JLabel label = null;
            if(statusIcons.containsKey(connCheckers[i])){
                label = (JLabel)statusIcons.get(connCheckers[i]);
            }else{
                label = new JLabel();
                statusIcons.put(connCheckers[i], label);
                connCheckers[i].addConnStatusChangedListener(this);
                newChecker = true;
            }
            if(status.getStatus() == ConnStatus.SUCCESSFUL ) label.setIcon(green);
            else if(status.getStatus() == ConnStatus.TRYING ) label.setIcon(yellow);
            else if(status.getStatus() == ConnStatus.UNKNOWN) label.setIcon(blue);
            else label.setIcon(red);
        }
        if(newChecker){
            createGUI();
        }
    }
    
    private void createGUI() {
        removeAll();
        JButton retryButton = new JButton("Retry Connections");
        JPanel endPanel = new JPanel();
        endPanel.setLayout(new FlowLayout());
        endPanel.add(retryButton);
        
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.weightx = 1.0;
        constraints.weighty = 1.0;
        constraints.gridy = 0;
        constraints.fill = constraints.HORIZONTAL;
        
        Iterator iter = statusIcons.keySet().iterator();
        logger.debug("The size of the statusIcons is "+statusIcons.size());
        
        while(iter.hasNext()) {
            ConnChecker key = (ConnChecker) iter.next();
            JLabel keyLabel = new JLabel(key.toString());
            JLabel addLabel = (JLabel) statusIcons.get(key);
            constraints.gridx = 0;
            grid.setConstraints(keyLabel, constraints);
            this.add(keyLabel);
            constraints.gridx = constraints.gridx + 1;
            grid.setConstraints(addLabel, constraints);
            this.add(addLabel);
            constraints.gridy = constraints.gridy + 3;
        }
        
        constraints.gridwidth = 2;
        constraints.gridx = 0;
        
        JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL);
        //logger.debug("The string is "+str);
        grid.setConstraints(separator, constraints);
        this.add(separator);
        
        constraints.gridwidth = 1;
        constraints.gridy = constraints.gridy + 1;
        JLabel label = new JLabel("successful", green, JLabel.LEFT);
        grid.setConstraints(label, constraints);
        this.add(label);
        
        constraints.gridx = constraints.gridx + 1;
        label = new JLabel("trying", yellow, JLabel.LEFT);
        grid.setConstraints(label, constraints);
        this.add(label);
        
        constraints.gridx = 0;
        constraints.gridy = constraints.gridy + 1;
        label = new JLabel("unknown", blue, JLabel.LEFT);
        grid.setConstraints(label, constraints);
        this.add(label);
        
        constraints.gridx = constraints.gridx + 1;
        label = new JLabel("failed", red, JLabel.LEFT);
        grid.setConstraints(label, constraints);
        this.add(label);
        
        constraints.gridx = 0;
        constraints.gridwidth = 2;
        constraints.gridy = constraints.gridy + 1;
        grid.setConstraints(endPanel, constraints);
        this.add(endPanel);
        retryButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        CommonAccess ca = CommonAccess.getCommonAccess();
                        ca.getChecker().runChecks();
                    }
                });
        revalidate();
    }
    
    private Map params;
    
    private ImageIcon green, red, yellow, blue;
    
    private Map statusIcons = new HashMap();
    
    private static boolean built = false;
    
    private GridBagLayout grid = new GridBagLayout();
    
    private static Logger logger = Logger.getLogger(ConnectionStatusTask.class);
}// ConnectionStatusTask
