package edu.sc.seis.gee.task;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.iris.Fissures.IfNetwork.Station;
import edu.sc.seis.fissuresUtil.chooser.ChannelChooser;
import edu.sc.seis.fissuresUtil.chooser.StationSelectionEvent;
import edu.sc.seis.fissuresUtil.chooser.StationSelectionListener;
import edu.sc.seis.gee.CommonAccess;
import edu.sc.seis.gee.NoNetworkException;
import edu.sc.seis.gee.configurator.ConfigurationException;

public class StationSelectionTask implements Task, StationSelectionListener{


    private List stationStrings = new ArrayList();
    private Station[] selectedStations = new Station[0];
    private ChannelChooser chooser  = null;
    private ChannelChooserTask chooserTask;
    private boolean printSelectedConfig = false;

    /**
     * Configures a <code>Task</code> with any needed parameters. The Task
     * should have default values for as many things as possible, but can
     * throw a ConfigureException if a required parameter is missing.
     *
     * @param params a <code>Map</code> value
     * @exception ConfigurationException if an error occurs
     */
    public void configure(Map params) throws ConfigurationException {
        if (params.containsKey("channelChooserTask")){
            String chooserID = (String)params.get("channelChooserTask");
            if (chooserID == null || chooserID.length() == 0){
                throw new ConfigurationException("ChannelChooserTask not set in config");
            }
            TaskAction taskAction = CommonAccess.getCommonAccess().getTaskAction(chooserID);
            chooserTask = (ChannelChooserTask)taskAction.getTask();
        }
        else throw new ConfigurationException("ChannelChooserTask not found in config");

        Set keys = params.keySet();
        Iterator it = keys.iterator();
        while (it.hasNext()){
            String current = (String)it.next();
            if (current.startsWith("Station_")){
                String currentStation = (String)params.get(current);
                stationStrings.add(currentStation);
                System.out.println("station added from config: " + currentStation);
            }
        }

        if (params.containsKey("printSelectedConfig")){
            String boolString = (String)params.get("printSelectedConfig");
            if (boolString.equals("true")){
                printSelectedConfig = true;
            }
        }
    }

    /**
     * Called when a task is to be executed, usually by a menu or toolbar
     * selection for simple tasks.
     *
     *
     * @exception Exception if an error occurs
     */
    public void invoke() throws Exception {
        //debugging stuff for filtering duplicate stations
//      System.out.println("--Currently in stationStrings:--");
//      for (int i = 0; i < stationStrings.size(); i++) {
//          System.out.println((String)stationStrings.get(i));
//      }
//      System.out.println("--------------------------------");
//
//      //deselecting selected stations
//      for (int i = 0; i < selectedStations.length; i++) {
//          chooser.toggleStationSelected(selectedStations[i]);
//      }
        getChannelChooser().clearStationSelection();

        Station[] allStations = getChannelChooser().getStations();
        for (int i = 0; i < allStations.length; i++) {
            String currentStationString =
                allStations[i].getNetworkAttr().get_code() + "." + allStations[i].get_code();
            if (stationStrings.contains(currentStationString)){
                getChannelChooser().toggleStationSelected(allStations[i]);
            }
        }
    }

    /**
     * Called when reset is invoked on gee or if this task is no longer being used
     *
     */
    public void destroy() {}

    public ChannelChooser getChannelChooser() throws NoNetworkException {
        if (chooser == null) {
            chooser = chooserTask.getChannelChooser();
            chooser.addStationSelectionListener(this);
        }
        return chooser;
    }

    /**
     * Method stationSelectionChanged
     *
     * @param    s                   a  StationSelectionEvent
     *
     */
    public void stationSelectionChanged(StationSelectionEvent s) {
        if (printSelectedConfig){
            selectedStations = s.getSelectedStations();
            printSelectedStations();
        }
//      //removing duplicate stations because of a bug in the ChannelChooser
//      int numDuplicates = 0;
//      for (int i = selectedStations.length - 1; i >= 0; i--) {
//          if (selectedStations[i] != null){
//              String curStaCodeI = selectedStations[i].my_network.get_code() + "." + selectedStations[i].get_code();
//              for (int j = i - 1; j >= 0; j--) {
//                  if (selectedStations[j] != null){
//                      String curStaCodeJ = selectedStations[j].my_network.get_code() + "." + selectedStations[j].get_code();
//                      if (curStaCodeJ.equals(curStaCodeI)){
//                          selectedStations[j] = null;
//                          numDuplicates++;
//                      }
//                  }
//              }
//          }
//      }
//
//      Station[] nonNulSelSta = new Station[selectedStations.length - numDuplicates];
//      int nonNullIndex = 0;
//      for (int i = 0; i < selectedStations.length; i++) {
//          if (selectedStations[i] != null){
//              nonNulSelSta[nonNullIndex] = selectedStations[i];
//              nonNullIndex++;
//          }
//      }
//      selectedStations = nonNulSelSta;
//      printSelectedStations();
    }

    private void printSelectedStations(){
        System.out.println("\t\t<!--Selected Stations from ChannelChooser-->");
        for (int i = 0; i < selectedStations.length; i++) {
                System.out.println("\t\t<taskconfig>");
                System.out.println("\t\t\t<name>Station_" + i + "</name>");
                System.out.println("\t\t\t<value>" + selectedStations[i].getNetworkAttr().get_code() + "." + selectedStations[i].get_code() + "</value>");
                System.out.println("\t\t</taskconfig>");
        }
        System.out.println("\t\t<!--end of selected stations-->");
    }
}
