/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/01/30, 10:47
!  AUTHOR(S): KOGA, Junichiro
!  File : ImageViewerBooter.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.io.BufferedReader;
import java.io.File;

import org.apache.log4j.Logger;

import ciss.phase_viewer.common.ExternalProgramExecuter;
import ciss.phase_viewer.common.Utils;
import ciss.phase_viewer.settings.GlobalProperties;
import ciss.phase_viewer.settings.PropertiesManager;

/**
 * イメージファイルビューアーをブートするクラス.
 * 
 * @author
 */
public class ImageViewerBooter implements Runnable {
    private Logger logger = Logger.getLogger(ImageViewerBooter.class.getName());
    private int res = 150;
    private int pageNum;
    private String[] files;

    /**
     * bootしたいファイルのパスを渡す.
     * 
     * @param files
     *            眺めたいイメージファイルへのパス
     */
    public ImageViewerBooter(String file) {
        this.files = new String[] { file };
    }

    /**
     * bootしたいファイルのパスを渡す.
     * 
     * @param files
     *            眺めたいイメージファイルへのパス
     */
    public ImageViewerBooter(String[] files) {
        this.files = files;
    }

    /**
     * bootしたいファイルへのパスと, ps,eps,pdfファイルの場合の変換の解像度を指定する.
     * 
     * @param res
     *            ps,eps,pdfファイルの場合の変換の解像度
     * @param files
     *            表示したいファイルへのパスの配列
     */
    public ImageViewerBooter(int res, String[] files) {
        this.res = res;
        this.files = files;
    }

    public void run() {
        if (files == null || files.length == 0) {
            logger.info("no files selected");
            return;
        }
        GlobalProperties gp = PropertiesManager
                .getGlobalProperties(PropertiesManager.PROPERTIES_PVIEWER);
        try {
            res = Integer.parseInt(gp
                    .getProperty("image_viewer_default_resolution"));
        } catch (Exception exc) {
        }
        try {
            for (int i = 0; i < files.length; i++) {
                String infileName = files[i];
                String[] pageArray = null;
                String originalName = infileName;
                if (infileName.toLowerCase().trim().endsWith(".eps")
                        || infileName.toLowerCase().trim().endsWith(".ps")
                        || infileName.toLowerCase().trim().endsWith(".pdf")) {
                    pageArray = getTemporaryImageFile(infileName);
                    if (pageArray != null && pageArray.length != 0) {
                        infileName = pageArray[0];
                    } else {
                        logger.error("invalid ps/eps/pdf file");
                        return;
                    }
                }

                if (!(new File(infileName)).exists()) {
                    logger.error("file does not exist!");
                    continue;
                }

                MainPanel mp = new MainPanel(infileName, originalName);
                if (mp.getStatus()) {
                    mp.setPageNum(pageNum);
                    pageNum = 0;
                    if (pageArray != null) {
                        mp.setPageArray(pageArray);
                    }
                    mp.display();
                    mp.requestFocus();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("failed to boot image viewer");
        }
    }

    /**
     * ps, eps, pdfファイルについては, 一度png形式の画像ファイルに変換してから表示を行う
     * (その変換にはghostscriptを使用する). その変換操作を行うメソッド. 変換後の ファイルは,
     * プログラム終了時に削除されるよう設定している.
     * 
     * @return 変換後の画像ファイルへのパスを保持した配列.
     */
    public String[] getTemporaryImageFile(String infileName) {
        String FS = System.getProperty("file.separator");
        File infileFile = new File(infileName);
        String fileName = infileFile.getName();
        // String tmpDir = System.getProperty("user.home")+FS+".phase-viewer";
        String tmpDir = System.getProperty("user.home") + FS + ".phase-viewer";
        String imageFile = tmpDir + FS + fileName;
        String imageFileIn = Utils.getPathDQ(imageFile + "%d.png");
        infileName = Utils.getPathDQ(infileName);

        String epsCrop = "";
        if (fileName.trim().toLowerCase().endsWith(".eps")) {
            epsCrop = "-dEPSCrop";
        }

        String gs = PropertiesManager.getGlobalProperties(
                PropertiesManager.PROPERTIES_PVIEWER).getProperty("gs");
        String gsExe = Utils.getPathDQ(gs)
                + " -q -dNOPROMPT -dBATCH -sDEVICE=png16m -r" + res + " "
                + epsCrop + " -dNOPAUSE -sOutputFile=" + imageFileIn + " "
                + infileName;

        logger.info("gsexe: " + gsExe);
        BufferedReader[] br = new BufferedReader[2];
        try {
            String str;
            br = ExternalProgramExecuter.executeGetBR(gsExe, true);
            br[0].close();
            br[1].close();
        } catch (Exception e) {
            // e.printStackTrace();
            // logger.error("failed to run gs.");
        }

        while (true) {
            pageNum++;
            File pageFile = new File(imageFile + pageNum + ".png");
            if (pageFile.exists()) {
                pageFile.deleteOnExit();
            } else {
                pageNum--;
                break;
            }
        }
        logger.info("number of pages: " + pageNum);
        String[] tmpImageFiles = new String[pageNum];
        for (int i = 0; i < pageNum; i++) {
            int ii = i + 1;
            tmpImageFiles[i] = imageFile + ii + ".png";
        }

        return tmpImageFiles;
    }

    /**
     * 指定のファイルがイメージファイルか否かを判定; ファイル名のみの判定であることに注意!!
     * 
     * @param fileName
     *            判定したいファイルのファイル名
     * @return イメージファイルならtrue.
     */
    public static boolean isImageFile(String name) {
        String lower = name.toLowerCase();
        if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")
                || lower.endsWith(".png") || lower.endsWith(".eps")
                || lower.endsWith(".ps") || lower.endsWith(".pdf")
                || lower.endsWith(".gif") || lower.endsWith(".tif")
                || lower.endsWith(".tiff") || lower.endsWith(".bmp"))
            return true;
        else
            return false;
    }

}
