/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/11/11, 19:31
!  AUTHOR(S): KOGA, Junichiro
!  File : ImageLoaderPanel.java
!  
!  Contact address :  Phase System Consortium
!                     E-mail: phase_system@nims.go.jp URL https://azuma.nims.go.jp
!
!
!   Since 2002, this program set had been intensively developed as a part of the following 
!  national projects supported by the Ministry of Education, Culture, Sports, Science and
!  Technology (MEXT) of Japan; "Frontier Simulation Software for Industrial Science
!  (FSIS)" from 2002 to 2005, "Revolutionary Simulation Software (RSS21)" from 2006 to
!  2008. "Research and Development of Innovative Simulation Software (RISS)" from 2008
!  to 2013. These projects is lead by the Center for Research on Innovative Simulation 
!  Software (CISS), the Institute of Industrial Science (IIS), the University of Tokyo.
!   Since 2013, this program set has been further developed centering on PHASE System
!  Consortium. 
!   The activity of development of this program set has been supervised by Takahisa Ohno.
!
!=======================================================================
 */

package ciss.phase_viewer.imageviewer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import ciss.phase_viewer.common.ChaseFileChooser;
import ciss.phase_viewer.inputinterface.filestate.FileStateChangeEvent;
import ciss.phase_viewer.inputinterface.filestate.FileStateListener;
import ciss.phase_viewer.inputinterface.filestate.FileStateObserver;
import ciss.phase_viewer.settings.GlobalProperties;
import ciss.phase_viewer.settings.PropertiesManager;

/**
 * 指定のディレクトリー下のイメージファイルを表示, 必要に応じviewerをboot.
 * 
 * @author
 */
public class ImageLoaderPanel extends JPanel implements FileStateListener {
    private Logger logger = Logger.getLogger(ImageLoaderPanel.class.getName());

    private String dir;
    private Vector imagefiles_wk;
    private String[] imagefiles;
    private String[] imagefiles_selected;
    private JTextArea labeldir;
    private File file;
    private JButton btndir;
    private JButton btnshow;
    private JButton btnclose;
    private JPanel plist;
    private JPanel pbtn;
    private JList list;
    private JScrollPane scrpane;

    private final String DEFAULT_RESOLUTION = "100";

    private JTextField ipres;
    private int pageNum = 0;
    private int page = 0;

    /** Creates a new instance of ImageLoaderPanel */
    public ImageLoaderPanel(String dir) {
        this.dir = dir;
        file = new File(dir);
        init();
        if (file.exists() && file.isDirectory()) {
            FileStateObserver obs = new FileStateObserver(dir,
                    new String[] { ".+" });
            obs.addFileStateListener(this);
        }
    }

    private void init() {
        JPanel p = this;

        setImageFiles();
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));

        JPanel textPanel = new JPanel();
        textPanel.setLayout(new BorderLayout());
        // textPanel.setLayout(new BoxLayout(textPanel,BoxLayout.X_AXIS));
        ipres = new JTextField(12);
        GlobalProperties gp = PropertiesManager
                .getGlobalProperties(PropertiesManager.PROPERTIES_PVIEWER);
        String res = DEFAULT_RESOLUTION;
        try {
            res = gp.getProperty("image_viewer_default_resolution");
        } catch (Exception exc) {
        }
        ipres.setText(res);

        textPanel
                .add(new JLabel("resolution(ps,eps,pdf): "), BorderLayout.WEST);
        textPanel.add(ipres, BorderLayout.CENTER);
        JPanel panel2 = new JPanel();
        panel2.add(textPanel);
        file = new File(dir);

        JLabel labeldir = new JLabel("current directory: " + file.toString());
        labeldir.setBackground(Color.cyan);
        labeldir.setForeground(Color.blue);

        p.add(labeldir);

        list = new JList(imagefiles);
        Font font = new Font("Serif", Font.PLAIN, 14);
        list.setFont(font);
        scrpane = new JScrollPane(list);
        p.add(scrpane);

        JButton btndir = new JButton("select directory");
        JButton btnshow = new JButton("show selected image(s)");

        pbtn = new JPanel();
        pbtn.setLayout(new BoxLayout(pbtn, BoxLayout.X_AXIS));
        pbtn.add(panel2, BorderLayout.WEST);
        pbtn.add(btndir, BorderLayout.CENTER);
        pbtn.add(btnshow, BorderLayout.EAST);

        p.add(pbtn);

        btnshow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bootImageViewer();
            }
        });

        btndir.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                selectDir();
                redraw();
            }
        });

        list.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                if (me.getButton() == MouseEvent.BUTTON1
                        && me.getClickCount() == 2) {
                    bootImageViewer();
                }
            }
        });

        list.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent ke) {
                if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
                    bootImageViewer();
                }
            }
        });

    }

    private void bootImageViewer() {
        logger.info("booting imageviewer ...");
        if (list.getSelectedValues().length > 0) {
            if (!(dir.endsWith(File.separator))) {
                dir = dir + File.separator;
            }
            imagefiles_selected = new String[list.getSelectedValues().length];
            for (int i = 0; i < list.getSelectedValues().length; i++) {
                imagefiles_selected[i] = dir
                        + list.getSelectedValues()[i].toString();
            }
            int ires = 100;
            String res = ipres.getText();
            try {
                ires = Integer.parseInt(res);
            } catch (Exception exc) {
                ires = 100;
            }
            ImageViewerBooter bt = new ImageViewerBooter(ires,
                    imagefiles_selected);
            new Thread(bt).start();
        }
    }

    private void setImageFiles() {
        int i;
        if (file.isDirectory()) {
            imagefiles_wk = new Vector();
            for (i = 0; i < file.list().length; i++) {
                String name = file.list()[i];
                if (name.toLowerCase().endsWith(".jpg")
                        || name.toLowerCase().endsWith(".jpeg")
                        || name.toLowerCase().endsWith(".png")
                        || name.toLowerCase().endsWith(".eps")
                        || name.toLowerCase().endsWith(".ps")
                        || name.toLowerCase().endsWith(".pdf")
                        || name.toLowerCase().endsWith(".gif")
                        || name.toLowerCase().endsWith(".tif")
                        || name.toLowerCase().endsWith(".tiff")
                        || name.toLowerCase().endsWith(".bmp")) {
                    imagefiles_wk.addElement(name);
                }
            }

            imagefiles = new String[imagefiles_wk.size()];
            for (i = 0; i < imagefiles_wk.size(); i++) {
                imagefiles[i] = (String) imagefiles_wk.get(i);
            }
        } else {
            imagefiles = new String[1];
            imagefiles[0] = "";
        }
    }

    private void selectDir() {
        ChaseFileChooser fdlg = new ChaseFileChooser(ChaseFileChooser.media);
        fdlg.setDialogType(JFileChooser.CUSTOM_DIALOG);
        fdlg.setDialogTitle("Open");
        fdlg.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (fdlg.showDialog(this, "open") != JFileChooser.APPROVE_OPTION) {
            return;
        }
        this.dir = fdlg.getSelectedFile().getAbsolutePath();
        file = new File(dir);
    }

    private void redraw() {
        removeAll();
        init();
        revalidate();
    }

    public void fileStateChanged(FileStateChangeEvent fe) {
        redraw();
    }

}
