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

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import ciss.phase_viewer.common.ChaseFileChooser;
import ciss.phase_viewer.common.ExternalProgramExecuter;
import ciss.phase_viewer.common.MyMessageBox;
import ciss.phase_viewer.mainpanel.Desk;
import ciss.phase_viewer.mainpanel.InternalFrameChase;
import ciss.phase_viewer.settings.GlobalProperties;
import ciss.phase_viewer.settings.PropertiesManager;

public class ActivationPanel extends InternalFrameChase {
    String lcg = "advanceLCG";
    String FS = System.getProperty("file.separator");
    String LS = System.getProperty("line.separator");

    MyMessageBox mbox = new MyMessageBox();
    GlobalProperties property = PropertiesManager
            .getGlobalProperties(PropertiesManager.PROPERTIES_PVIEWER);

    public ActivationPanel() {
        super("activate", true, true, true, true);
        this.setSize(200, 100);
        Container container = this.getContentPane();
        container.add(createButtons());
    }

    public void display() {
        System.out.println("displaying activation panel ...");
        this.setVisible(true);
    }

    private JPanel createButtons() {
        JPanel pbtn = new JPanel();
        // pbtn.setLayout(new FlowLayout());
        // pbtn.setLayout(new BoxLayout(pbtn,BoxLayout.Y_AXIS));
        pbtn.setLayout(new GridLayout(3, 1));
        JButton btnBootLCG = new JButton("get Locking Code");
        JButton btnSelectLF = new JButton("select license file");
        JButton btnClose = new JButton("close");
        pbtn.add(btnBootLCG);
        pbtn.add(btnSelectLF);
        pbtn.add(btnClose);

        btnBootLCG.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String exec = System.getProperty("pviewer.home") + FS
                        + property.getProperty("lcgpath") + FS + lcg;
                if (System.getProperty("os.name").trim().toLowerCase()
                        .startsWith("windows")) {
                    exec += ".exe";
                }
                if ((new File(exec)).exists()) {
                    bootLCG(exec);
                } else {
                    mbox.setText("couldn't find locking code generator!");
                }
            }
        });

        btnSelectLF.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                selectLF();
            }
        });

        btnClose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        return pbtn;
    }

    private void bootLCG(String exec) {
        BufferedReader[] bin;
        try {
            bin = ExternalProgramExecuter.executeGetBR(exec);
        } catch (Exception exc) {
            exc.printStackTrace();
            mbox.setText("failed execution of: " + exec);
            return;
        }

        String string;
        String acumString = new String();
        try {
            while ((string = bin[0].readLine()) != null) {
                acumString += string + LS;
            }
        } catch (Exception exc) {
            exc.printStackTrace();
            return;
        }

        System.out.println(acumString);
        JOptionPane.showMessageDialog(Desk.getDesktop(), acumString,
                "advanceLCG", JOptionPane.PLAIN_MESSAGE);
        this.deleteAnnoyingFiles();
    }

    private void selectLF() {
        String lfpath = System.getProperty("pviewer.home") + FS
                + property.getProperty("licensefilepath");
        ChaseFileChooser fdlg = new ChaseFileChooser();
        fdlg.setDialogType(JFileChooser.CUSTOM_DIALOG);
        fdlg.setDialogTitle("select");
        fdlg.setFileSelectionMode(JFileChooser.FILES_ONLY);
        if (fdlg.showDialog(this, "open") != JFileChooser.APPROVE_OPTION) {
            return;
        }
        String copyFrom = fdlg.getSelectedFile().getAbsolutePath();
        String selectedFileName = (new File(copyFrom)).getName();
        String copyTo = lfpath + FS + selectedFileName;

        if (!copyTo.trim().equals(copyFrom.trim())) {
            try {
                ExternalProgramExecuter.copy(copyFrom, copyTo);
                mbox.setText("successfully copied file " + copyFrom + " to "
                        + copyTo);
            } catch (Exception exc) {
                return;
            }
        } else {
            mbox.setText("same file!");
        }

    }

    private void deleteAnnoyingFiles() {
        String[] files = { "clauth1.dll", "clauth2.dll", "lsprst7",
                "ssprs.dll", "ssprs.tgz", "sysprs7", "sysprs7.tgz",
                "lsprst7.tgz" };
        String pwd = System.getProperty("user.dir");
        for (int i = 0; i < files.length; i++) {
            String delfile = pwd + System.getProperty("file.separator")
                    + files[i];
            (new File(delfile)).delete();
        }
    }

}
