/*
 * 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.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.AccessControlException;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import ilog.views.IlvManagerView;
import ilog.views.maps.IlvMapUtil;
import ilog.views.maps.beans.IlvExceptionMessage;
import ilog.views.maps.datasource.IlvMapDataSource;
import ilog.views.maps.format.dted.IlvRasterDTEDReader;
import ilog.views.maps.raster.IlvRasterAbstractReader;
import ilog.views.maps.raster.datasource.IlvRasterDataSourceFactory;
import ilog.views.maps.raster.datasource.IlvThreadMonitoringData;

/**
 * Class that manages DTED import action.
 */
public class DTEDLoadAction extends DefaultLoadAction {
  /**
   * Creates an action for the specified view
   * 
   * @param view
   *          view to add map data to.
   */
  public DTEDLoadAction(IlvManagerView view) {
    super(view);
  }

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

  /**
   * @see plugins.DefaultLoadAction#makeReader(java.lang.String)
   */
  Override
  public IlvRasterAbstractReader makeReader(String fileName) {
    return makeReader(new String[] { fileName }, null);
  }

  /**
   * @see plugins.DefaultLoadAction#makeReader(URL)
   */
  Override
  public IlvRasterAbstractReader makeReader(URL url) throws IOException {
    IlvRasterDTEDReader r = new IlvRasterDTEDReader();
    r.addMap(url);
    return r;
  }

  /**
   * @param monitorData
   * @see plugins.DefaultLoadAction#makeReader(java.lang.String)
   */
  IlvRasterAbstractReader makeReader(String[] fileNames, IlvThreadMonitoringData monitorData) {
    Vector<String> fileList = new Vector<String>();
    boolean asked = false;
    IlvRasterDTEDReader r = new IlvRasterDTEDReader();
    for (int j = 0; j < fileNames.length; j++) {
      compileDTEDImages(fileNames[j], fileList);
      if (fileList.size() > 1000 && !asked) {
        asked = true;
        int ans = JOptionPane.showConfirmDialog(getView(),
            IlvMapUtil.getString(getClass(), "DTEDLoadAction.TooManyFiles")); //$NON-NLS-1$
        if (ans == JOptionPane.NO_OPTION) {
          break;
        } else if (ans != JOptionPane.YES_OPTION) {
          return null;
        }
      }
    }
    int size = fileList.size();
    LoadDataRunnable runnable = null;
    if (Thread.currentThread() instanceof LoadDataRunnable) {
      runnable = (LoadDataRunnable) Thread.currentThread();
    }
    for (int i = 0; i < size; i++) {
      try {
        r.addMap((String) fileList.get(i));
        if (monitorData != null) {
          int percent = Math.round(i / (float) size * 100);
          monitorData.updateProgress(percent);
        }
      } catch (IOException e) {
        String errorMsg = IlvMapUtil.getString(getClass(), "DTEDLoadAction.Error"); //$NON-NLS-1$
        new IlvExceptionMessage(e, errorMsg + (String) fileList.get(i));
      }
      if (runnable != null) {
        if (runnable.wasStoppedCleanly()) {
          if (monitorData != null) {
            monitorData.updateProgress(100);
          }
          break;
        }
      }
    }
    return r;
  }

  /**
   * @see plugins.DefaultLoadAction#getExtensions()
   */
  Override
  public String[] getExtensions() {
    return new String[] { ".dt0", //$NON-NLS-1$
        ".dt1", //$NON-NLS-1$
        ".dt2", //$NON-NLS-1$
        ".dt3" }; //$NON-NLS-1$
  }

  private void compileDTEDImages(String fileName, Vector<String> fileList) {
    File f = new File(fileName);
    boolean dir = false;
    try {
      dir = f.isDirectory();
    } catch (AccessControlException e) {
      // applets.
    }
    if (dir) {
      File sub[] = f.listFiles();
      for (int i = 0; i < sub.length; i++) {
        compileDTEDImages(sub[i].getPath(), fileList);
      }
    } else if (accept(f)) {
      fileList.add(fileName);
    }
  }

  /**
   * Loads data by creating a data source with a specific reader for each of the
   * files passed.
   * 
   * @see #makeReader(String)
   * @see plugins.ImportAction#getDataSources(java.lang.String[])
   */
  Override
  public Enumeration<IlvMapDataSource> getDataSources(String fileNames[]) {
    return new FileTableLoader(fileNames, this) {
      /**
       * @see java.util.Enumeration#nextElement()
       */
      Override
      public IlvMapDataSource nextElement() {
        if (hasMoreElements()) {
          // int i=currentFile;
          // File f=new File(fileNames[i]);
          String name = new File((String) fileNames[currentFile]).getName() + "~" //$NON-NLS-1$
              + new File((String) fileNames[fileNames.length - 1]).getName();
          IlvThreadMonitoringData monitorData = new IlvThreadMonitoringData(importAction.getMonitor(), fileNames,
              name + " " + importAction.getActivityDescription(RENDERING), 0, 100); //$NON-NLS-1$

          IlvMapDataSource dataSource;
          IlvRasterAbstractReader r = ((DTEDLoadAction) importAction).makeReader((String[]) fileNames, monitorData);
          if (r != null) {
            dataSource = IlvRasterDataSourceFactory.buildTiledImageDataSource(importAction.getView().getManager(), r,
                true, true, monitorData);
            dataSource.setName(importAction.getFormatName() + " " + name); //$NON-NLS-1$
            currentFile = this.fileNames.length;
            return dataSource;
          }
        }
        return null;
      }
    };
  }

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

  /**
   * @see plugins.DefaultLoadAction#getFormatName()
   */
  Override
  public String getFormatName() {
    return ilog.views.maps.IlvMapUtil.getString(getClass(), "DTEDLoadAction.FormatName"); //$NON-NLS-1$
  }

  /**
   * @see plugins.ImportAction#approveSelection(java.io.File[])
   */
  Override
  public boolean approveSelection(File selection[]) {
    if (selection.length == 1) {
      if (selection[0].getParent() == null)
        return false;
    }
    return super.approveSelection(selection);
  }
}