/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on ----
!  AUTHOR(S): KOGA, Junichiro
!  File : MovieMakerPanel.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.plugins.viewer.frame;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import org.apache.log4j.Logger;

import ciss.phase_viewer.acviewer.Animater;
import ciss.phase_viewer.common.ChooserButton;
import ciss.phase_viewer.common.SimpleHeavyGUI;
import ciss.phase_viewer.movie.MovieViewer;

class MovieMakerPanel extends SimpleHeavyGUI {
    private static Logger logger = Logger.getLogger(MovieMakerPanel.class
            .getName());
    private Animater animater;

    private MovieMaker movieMaker;

    private JCheckBox cbjpegs;
    private JCheckBox cbmov;

    private String baseDir = System.getProperty("user.home");
    private JTextField basetext;

    private JTextField prefix;
    private JTextField filename;
    private JTextField filenamevrml;

    private JTextField framerate;

    private JComboBox combotype;

    protected MovieMakerPanel(MovieMaker movieMaker) {
        super("movie maker", "create movie", "close", new Dimension(500, 330));
        this.addViewerButton();
        this.movieMaker = movieMaker;
        this.animater = movieMaker.getAssociatedAnimater();
        basetext.setText(this.baseDir);
    }

    protected MovieMakerPanel(MovieMaker movieMaker, String baseDir) {
        super("movie maker", "create movie", "close", new Dimension(500, 330));
        this.addViewerButton();
        this.movieMaker = movieMaker;
        this.animater = movieMaker.getAssociatedAnimater();
        this.baseDir = baseDir;
        basetext.setText(this.baseDir);
    }

    private void addViewerButton() {
        JButton view = new JButton("view created movie");
        super.addButtons(view, 1);
        view.requestFocus();
        view.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bootMovieViewer();
            }
        });

        basetext.addCaretListener(new CaretListener() {
            public void caretUpdate(CaretEvent e) {
                animater.setBaseDir(basetext.getText());
                movieMaker.setBaseDir(basetext.getText());
            }
        });

        filename.addCaretListener(new CaretListener() {
            public void caretUpdate(CaretEvent e) {
                movieMaker.setMovieFileName(filename.getText());
            }
        });
    }

    private void bootMovieViewer() {
        logger.info("booting movie viewer ...");
        String mf = movieMaker.getMovieFileName();
        if (mf == null || !(new File(mf)).exists()) {
            logger.warn("couldn't find file: " + mf);
            return;
        }
        MovieViewer viewer = new MovieViewer("file:" + mf);
        viewer.setVisible(true);
    }

    private JPanel jpegPanel;
    private JPanel vrmlPanel;
    private JPanel optPanel;

    public JPanel createMainPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        JPanel basedirpanel = new JPanel();
        // basedirpanel.setLayout(new BoxLayout(basedirpanel,BoxLayout.X_AXIS));
        basedirpanel.setBorder(new TitledBorder("base directory"));

        basetext = new JTextField(System.getProperty("user.home"), 30);
        ChooserButton choose = new ChooserButton(ChooserButton.DIRECTORY,
                basetext);
        basedirpanel.add(basetext);
        basedirpanel.add(choose);

        combotype = new JComboBox(new String[] { "jpeg", "VRML" });
        JPanel typepanel = new JPanel();
        typepanel.setBorder(new TitledBorder("select movie file type"));
        typepanel.add(combotype);

        panel.add(basedirpanel);
        panel.add(typepanel);
        optPanel = new JPanel();
        panel.add(optPanel);

        JPanel prefixpanel = new JPanel();
        prefixpanel.setLayout(new BoxLayout(prefixpanel, BoxLayout.X_AXIS));
        prefixpanel
                .setBorder(new TitledBorder("prefix for numbered jpeg files"));
        prefix = new JTextField("frame", 20);
        prefixpanel.add(prefix);

        JPanel pmov = new JPanel();
        pmov.setLayout(new GridLayout(1, 2));
        pmov.setBorder(new TitledBorder("QuickTime movie"));

        JPanel cbpanel = new JPanel();
        cbpanel.setLayout(new BoxLayout(cbpanel, BoxLayout.Y_AXIS));

        cbmov = new JCheckBox("create QuickTime movie");
        cbmov.setSelected(true);

        JPanel pfiles = new JPanel();
        pfiles.setLayout(new BoxLayout(pfiles, BoxLayout.X_AXIS));
        cbjpegs = new JCheckBox("delete jpeg files");

        cbpanel.add(cbmov);
        cbpanel.add(cbjpegs);

        JPanel textpanel = new JPanel();
        textpanel.setLayout(new BoxLayout(textpanel, BoxLayout.Y_AXIS));
        JPanel frameratepanel = new JPanel();
        frameratepanel
                .setLayout(new BoxLayout(frameratepanel, BoxLayout.X_AXIS));
        frameratepanel.setBorder(new TitledBorder("frame rate (frames/sec)"));
        framerate = new JTextField("10", 20);
        frameratepanel.add(framerate);

        JPanel filenamepanel = new JPanel();
        filenamepanel.setLayout(new BoxLayout(filenamepanel, BoxLayout.X_AXIS));
        filenamepanel.setBorder(new TitledBorder("file name (.mov extention)"));
        filename = new JTextField("frame.mov", 20);
        filenamepanel.add(filename);

        JPanel filenamepanelvrml = new JPanel();
        filenamepanelvrml.setLayout(new BoxLayout(filenamepanelvrml,
                BoxLayout.X_AXIS));
        filenamepanelvrml.setBorder(new TitledBorder(
                "file name (.wrl extention)"));
        filenamevrml = new JTextField("frame.wrl", 20);
        filenamepanelvrml.add(filenamevrml);

        textpanel.add(frameratepanel);
        textpanel.add(filenamepanel);

        pmov.add(cbpanel);
        pmov.add(textpanel);

        jpegPanel = new JPanel();
        jpegPanel.setLayout(new BoxLayout(jpegPanel, BoxLayout.Y_AXIS));
        jpegPanel.add(prefixpanel);
        jpegPanel.add(pmov);

        vrmlPanel = new JPanel();
        vrmlPanel.setLayout(new BoxLayout(vrmlPanel, BoxLayout.Y_AXIS));
        vrmlPanel.add(filenamepanelvrml);
        vrmlPanel.add(frameratepanel);

        cbjpegs.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                movieMaker.jpegs = cbjpegs.isSelected();
            }
        });

        cbmov.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                boolean bmov = cbmov.isSelected();
                movieMaker.movs = bmov;
                cbjpegs.setEnabled(bmov);
                framerate.setEnabled(bmov);
                filename.setEnabled(bmov);
            }
        });

        combotype.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (combotype.getSelectedIndex() == 0) {
                    optPanel.removeAll();
                    optPanel.add(jpegPanel);
                    if (movieMaker != null)
                        movieMaker.setAnimMode(Animater.JPEG);
                } else if (combotype.getSelectedIndex() == 1) {
                    optPanel.removeAll();
                    optPanel.add(vrmlPanel);
                    if (movieMaker != null)
                        movieMaker.setAnimMode(Animater.VRML);
                }
                optPanel.revalidate();
                repaint();
            }
        });

        combotype.setSelectedIndex(0);

        return panel;
    }

    private String getMovieFileName() {
        String filenameString = "";
        if (combotype.getSelectedIndex() == 0) {
            filenameString = filename.getText().trim();
            if (!filenameString.endsWith(".mov")
                    && !filenameString.endsWith(".MOV")) {
                filenameString += ".mov";
            }
        } else if (combotype.getSelectedIndex() == 1) {
            filenameString = filenamevrml.getText().trim();
            if (!filenameString.toLowerCase().endsWith(".wrl")) {
                filenameString += ".wrl";
            }
        }
        return filenameString;
    }

    protected boolean action() {
        if (cbmov.isSelected() || combotype.getSelectedIndex() == 1) {
            int fr = 10;
            try {
                fr = Integer.parseInt(framerate.getText());
            } catch (NumberFormatException nfe) {
                logger.warn("set integer value for frame rate ... using the default value");
                fr = 10;
            }
            movieMaker.setFrameRate(fr);
            movieMaker.setImagePrefix(prefix.getText());
            String filenameString = getMovieFileName();
            movieMaker.setMovieFileName(filenameString);
        }

        String dir = basetext.getText();
        File dirdir = new File(dir);
        if (dirdir.mkdirs()) {
            logger.info("created directory: " + dir);
        }
        if (!dirdir.exists()) {
            logger.error("directory " + dir + " does not exsist.");
            return false;
        }
        movieMaker.setBaseDir(dir);
        movieMaker.createMovie();
        return true;
    }

}
