/*
 * Licensed Materials - Property of Perforce Software, Inc. 
 * © Copyright Perforce Software, Inc. 2014, 2021 
 * © Copyright IBM Corp. 2009, 2014
 * © Copyright ILOG 1996, 2009
 * All Rights Reserved.
 *
 * Note to U.S. Government Users Restricted Rights:
 * The Software and Documentation were developed at private expense and
 * are "Commercial Items" as that term is defined at 48 CFR 2.101,
 * consisting of "Commercial Computer Software" and
 * "Commercial Computer Software Documentation", as such terms are
 * used in 48 CFR 12.212 or 48 CFR 227.7202-1 through 227.7202-4,
 * as applicable.
 */

package plugins;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import ilog.views.IlvManagerView;
import ilog.views.maps.IlvMapUtil;
import ilog.views.maps.beans.IlvFeatureSelectorPanel;
import ilog.views.maps.datasource.IlvHierarchicalDataSource;
import ilog.views.maps.datasource.IlvMapDataSource;
import nodefense.VMAPDefLess;

/**
 * Class that manages VMAP import action.
 */
public class VMAPLoadAction extends ImportAction {

  IlvFeatureSelectorPanel featurePanel;
  JPanel compositePanel;
  TilingParameterPanel tilingPanel;
  boolean isLibrary = false;
  float lonMin = -180;
  float lonMax = 180;
  float latMin = -90;
  float latMax = 90;

  /**
   * Creates an action for the specified view
   * 
   * @param view
   *          view to add map data to.
   */
  public VMAPLoadAction(IlvManagerView view) {
    super(view);
  }

  /**
   * @see plugins.ImportAction#getSubDirectory()
   */
  Override
  protected String getSubDirectory() {
    return IlvMapUtil.getString(getClass(), "VMAPLoadAction.CDDirectory"); //$NON-NLS-1$
  }

  /**
   * @see plugins.ImportAction#selectedFileChanged(java.io.File)
   */
  Override
  public void selectedFileChanged(File file) {
    isLibrary = isVMAPDirectory(file);
    setEnabledComponent(compositePanel, isLibrary);
    setEnabledComponent(featurePanel, isLibrary);
  }

  /**
   * @see plugins.ImportAction#directoryChanged(java.io.File)
   */
  Override
  public void directoryChanged(File file) {
    selectedFileChanged(file);
  }

  /**
   * Convenience method to disable compound compoments.
   *
   * @param c
   *          the component to disable
   * @param enabled
   *          is the component enabled
   *
   */

  private void setEnabledComponent(JComponent c, boolean enabled) {
    Component[] compArray;
    if (c == null)
      return;
    compArray = c.getComponents();
    for (int i = 0; i < compArray.length; i++) {
      if (compArray[i] instanceof JComponent) {

        // else {
        ((JComponent) compArray[i]).setEnabled(enabled);
        if (compArray[i] instanceof JButton && !enabled) {
          ((AbstractButton) compArray[i]).setBackground(c.getBackground());
        }
        if (compArray[i] instanceof Container) {
          // Recurse
          setEnabledComponent((JComponent) compArray[i], enabled);
        }
        // }
      }
    }
  }

  /**
   * Checks if a directory can be a VMAP directory.
   * 
   * @param f
   *          directory
   * @return true if the directory could be a VMAP directory.
   */
  public boolean isVMAPDirectory(File f) {
    if (f == null)
      return false;
    String databasePath = f.getParent();
    String libraryName = f.getName();
    // IlvVMAPReader dummyReader = new IlvVMAPReader(databasePath);
    Object dummyReader = VMAPDefLess.newIlvVMAPReader(databasePath);
    // dummyReader.setLibraryName(libraryName);
    VMAPDefLess.setLibraryName(dummyReader, libraryName);
    String LATPath = databasePath + "/lat";//$NON-NLS-1$
    try {
      // IlvVMAPTable libraryAttributeTable = dummyReader.getVMAPTable(LATPath,
      // true);
      Object libraryAttributeTable = VMAPDefLess.getVMAPTable(dummyReader, LATPath, true);
      if (libraryAttributeTable == null) {
        return false;
      } // int currentLATRecordIndex =
        // libraryAttributeTable.searchRecordByColumnValue(1,
        // libraryName.toLowerCase());
      int currentLATRecordIndex = VMAPDefLess.searchRecordByColumnValue(libraryAttributeTable, 1,
          libraryName.toLowerCase());
      if (currentLATRecordIndex == -1) {
        return false;
      }
      // libraryAttributeTable.getRecord(currentLATRecordIndex);
      // Object[] currentLATRecord =
      // libraryAttributeTable.getRecord(currentLATRecordIndex);
      Object[] currentLATRecord = VMAPDefLess.getRecord(libraryAttributeTable, currentLATRecordIndex);

      // get library bounds
      lonMin = ((Float) currentLATRecord[2]).floatValue();
      latMin = ((Float) currentLATRecord[3]).floatValue();
      lonMax = ((Float) currentLATRecord[4]).floatValue();
      latMax = ((Float) currentLATRecord[5]).floatValue();
      // libraryAttributeTable.closeVMAPDataInput();
      VMAPDefLess.closeVMAPDataInput(libraryAttributeTable);
    } catch (Exception e1) {
      return false;
    }
    return true;
  }

  /**
   * return false.
   * 
   * @see plugins.ImportAction#isMultiSelectionEnabled()
   */
  Override
  public boolean isMultiSelectionEnabled() {
    return false;
  }

  /**
   * return DIRECTORIES_ONLY
   * 
   * @see plugins.ImportAction#getSelectionMode()
   */
  Override
  public int getSelectionMode() {
    return JFileChooser.DIRECTORIES_ONLY;
  }

  /**
   * @see plugins.ImportAction#getAccessory()
   */
  Override
  public JComponent getAccessory() {
    String filename = "VMAPFeaturesEN.xml"; //$NON-NLS-1$
    if (featurePanel == null) {
      featurePanel = new IlvFeatureSelectorPanel(null, filename, "VMAP");//$NON-NLS-1$
      // JScrollPane sp = new JScrollPane(featurePanel);
      // IlvDisplayPreferences prefs =
      // IlvDisplayPreferencesProperty.GetDisplayPreferences(getView().getManager());
      compositePanel = new JPanel(new BorderLayout());
      compositePanel.add(new JScrollPane(featurePanel), BorderLayout.CENTER);
      tilingPanel = new TilingParameterPanel(getView(), true);
      JButton boundsButton = new JButton(IlvMapUtil.getString(getClass(), "VMAPLoadAction.getBounds")); //$NON-NLS-1$
      boundsButton.addActionListener(new ActionListener() {
        Override
        public void actionPerformed(ActionEvent e) {
          tilingPanel.setBounds(Math.toRadians(latMin), Math.toRadians(lonMin), Math.toRadians(latMax),
              Math.toRadians(lonMax));
        }
      });
      JPanel subPanel = new JPanel(new BorderLayout());
      subPanel.add(tilingPanel, BorderLayout.CENTER);
      subPanel.add(boundsButton, BorderLayout.SOUTH);
      // compositePanel.add(tilingPanel,BorderLayout.SOUTH);
      compositePanel.add(subPanel, BorderLayout.SOUTH);
      // compositePanel.add(tilingPanel,BorderLayout.NORTH);

    }
    // File dirFile = new File(getDirectory());
    // selectedFileChanged(dirFile);

    compositePanel.setEnabled(isLibrary);

    return compositePanel;
  }

  /**
   * Not implemented for VMAP.
   * 
   * @throws IOException
   * @see plugins.ImportAction#getDataSources(URL[])
   */
  Override
  public Enumeration<IlvMapDataSource> getDataSources(URL urls[]) throws IOException {
    throw new IOException("getDataSources(URL} not implemented for this action " + getClass().getName()); //$NON-NLS-1$
  }

  /**
   * @see plugins.ImportAction#getDataSources(java.lang.String[])
   */
  Override
  public Enumeration<IlvMapDataSource> getDataSources(String fileNames[]) {
    Vector<IlvMapDataSource> src = new Vector<IlvMapDataSource>();
    for (int i = 0; i < fileNames.length; i++) {
      // IlvVMAPDataSource source = new IlvVMAPDataSource(fileNames[i]);
      IlvMapDataSource source = (IlvMapDataSource) VMAPDefLess.newVMAPDataSource(fileNames[i]);
      ((IlvHierarchicalDataSource) source).setAcceptNullValues(false);
      IlvFeatureSelectorPanel.Feature[] features = featurePanel.getSelectedFeatures();
      // String[] faccCodes = new String[features.length];
      List<String> faccCodes = new ArrayList<String>();
      if (features != null) {
        // for (int j = 0; j < features.length; j++) {
        // if (!features[j].getMinorCode().startsWith("-1")) { //$NON-NLS-1$
        // faccCodes.add(features[j].getMinorCode());
        // }
        // }
        for (int j = 0; j < features.length; j++) {
          IlvFeatureSelectorPanel.Feature currentFeature = features[j];
          IlvFeatureSelectorPanel.Feature currentChild;
          if (!currentFeature.getMinorCode().startsWith("-1")) { //$NON-NLS-1$
            faccCodes.add(features[j].getMinorCode());
          }
          for (int k = 0; k < currentFeature.getChildCount(); k++) {
            currentChild = (IlvFeatureSelectorPanel.Feature) currentFeature.getChildAt(k);
            faccCodes.add(currentChild.getMinorCode());
          }
        }
      }
      // source.setFaccCodeList((String[])faccCodes.toArray(new String[0]));
      VMAPDefLess.setFaccCodeList(source, (String[]) faccCodes.toArray(new String[0]));
      source.setManager(getView().getManager());
      // source.setAreaOfinterest(tilingPanel.getLonMin(),tilingPanel.getLatMin(),tilingPanel.getLonMax(),tilingPanel.getLatMax());
      VMAPDefLess.setAreaOfinterest(source, tilingPanel.getLonMin(), tilingPanel.getLatMin(), tilingPanel.getLonMax(),
          tilingPanel.getLatMax());
      // source.setTilingParameters(tilingPanel.isTiling(),tilingPanel.getRows(),tilingPanel.getColumns());
      VMAPDefLess.setTilingParameters(source, tilingPanel.isTiling(), tilingPanel.getRows(), tilingPanel.getColumns());

      source.setName(getFormatName() + " (" + new File(fileNames[i]).getName() + ")"); //$NON-NLS-1$//$NON-NLS-2$
      src.add(source);
    }
    return src.elements();
  }

  /**
   * @see plugins.ImportAction#approveSelection(File [])
   */
  Override
  public boolean approveSelection(File selection[]) {
    IlvFeatureSelectorPanel.Feature[] features = featurePanel.getSelectedFeatures();
    if (features == null || features.length == 0) {
      JOptionPane.showMessageDialog(view, IlvMapUtil.getString(VMAPLoadAction.class, "VMAPLoadAction.NoFeatureMessage"), //$NON-NLS-1$
          IlvMapUtil.getString(VMAPLoadAction.class, "VMAPLoadAction.NoFeatureTitle"), //$NON-NLS-1$
          JOptionPane.ERROR_MESSAGE);
      return false;
    }
    return super.approveSelection(selection);
  }

  /**
   * @see plugins.ImportAction#getFormatName()
   */
  Override
  public String getFormatName() {

    return ilog.views.maps.IlvMapUtil.getString(getClass(), "VMAPLoadAction.FormatName"); //$NON-NLS-1$
  }

  /**
   * @see javax.swing.filechooser.FileFilter#accept(java.io.File)
   */
  Override
  public boolean accept(File pathname) {
    boolean dir = false;
    try {
      dir = pathname.isDirectory();
    } catch (AccessControlException e) {
      // applets.
    }
    return (dir);
  }

  /**
   * @see plugins.ImportAction#getExtensions()
   */
  Override
  public String[] getExtensions() {
    return null; // select any directory
  }

  /**
   * @see plugins.ImportAction#isAvailable()
   */
  Override
  public boolean isAvailable() {
    return super.isAvailable() && VMAPDefLess.isAvailable();
  }
}