/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.fidentis.analyst.gui;

import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import cz.fidentis.analyst.Project;
import cz.fidentis.analyst.face.HumanFace;
import cz.fidentis.analyst.mesh.io.ModelFileFilter;
import cz.fidentis.analyst.newgui.Drawable;
import cz.fidentis.analyst.newgui.swing.CanvasTC;
import java.awt.Dimension;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 * The main panel enabling analysts to select the primary and secondary faces, 
 * and to perform basic batch processing. This panel also serves as an entry point 
 * for detailed face analysis and face-to-face comparison.
 * 
 * @author Matej Kovar
 */
@ConvertAsProperties(
        dtd = "-//cz.fidentis.analyst.gui//Dashboard//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "ProjectTopComp",
        //iconBase="SET/PATH/TO/ICON/HERE",
        persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "editor", openAtStartup = true)
@ActionID(category = "Window", id = "cz.fidentis.analyst.gui.ProjectTopComp")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_ProjectTopCompAction",
        preferredID = "ProjectTopComp"
)
@Messages({
    "CTL_ProjectTopCompAction=Project",
    "CTL_ProjectTopCompTopComponent=Project",
    "HINT_ProjectTopCompTopComponent=This is a Project window"
})
public final class ProjectTopComp extends TopComponent {

    private final Project project;
    private Map<HumanFace, CanvasTC> singleFaceTabs = new HashMap<>();

    
    /**
     * Creates new ProjectTopComp, initializes new project
     */
    public ProjectTopComp() {
        project = new Project();
        initComponents();
        setName(Bundle.CTL_ProjectTopCompTopComponent());
        setToolTipText(Bundle.HINT_ProjectTopCompTopComponent());
        putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_DRAGGING_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel5 = new javax.swing.JPanel();
        addButton1 = new javax.swing.JButton();
        removeButton1 = new javax.swing.JButton();
        selectAllButton1 = new javax.swing.JButton();
        deselectAllButton1 = new javax.swing.JButton();
        collapseButton1 = new javax.swing.JButton();
        inflateButton1 = new javax.swing.JButton();
        analyzeButton1 = new javax.swing.JButton();

        setLayout(new java.awt.BorderLayout());

        jPanel1.setBackground(new java.awt.Color(0, 174, 163));
        jPanel1.setPreferredSize(new java.awt.Dimension(0, 0));

        jPanel4.setBackground(new java.awt.Color(2, 138, 129));
        jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel2.setBackground(new java.awt.Color(0, 87, 87));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(204, 204, 204));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel4.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 30, 120, 120));

        jPanel5.setBackground(new java.awt.Color(2, 138, 129));
        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel5.setLayout(new java.awt.GridBagLayout());

        addButton1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(addButton1, org.openide.util.NbBundle.getMessage(ProjectTopComp.class, "ProjectTopComp.addButton1.text")); // NOI18N
        addButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                addButton1MouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 20;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(16, 16, 13, 4);
        jPanel5.add(addButton1, gridBagConstraints);

        removeButton1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(removeButton1, org.openide.util.NbBundle.getMessage(ProjectTopComp.class, "ProjectTopComp.removeButton1.text")); // NOI18N
        removeButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                removeButton1MouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(16, 22, 13, 4);
        jPanel5.add(removeButton1, gridBagConstraints);

        selectAllButton1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(selectAllButton1, org.openide.util.NbBundle.getMessage(ProjectTopComp.class, "ProjectTopComp.selectAllButton1.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(16, 22, 13, 4);
        jPanel5.add(selectAllButton1, gridBagConstraints);

        deselectAllButton1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(deselectAllButton1, org.openide.util.NbBundle.getMessage(ProjectTopComp.class, "ProjectTopComp.deselectAllButton1.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(16, 22, 13, 4);
        jPanel5.add(deselectAllButton1, gridBagConstraints);

        collapseButton1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(collapseButton1, org.openide.util.NbBundle.getMessage(ProjectTopComp.class, "ProjectTopComp.collapseButton1.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(16, 22, 13, 4);
        jPanel5.add(collapseButton1, gridBagConstraints);

        inflateButton1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(inflateButton1, org.openide.util.NbBundle.getMessage(ProjectTopComp.class, "ProjectTopComp.inflateButton1.text")); // NOI18N
        inflateButton1.setAlignmentX(0.5F);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(16, 22, 13, 4);
        jPanel5.add(inflateButton1, gridBagConstraints);

        analyzeButton1.setBackground(new java.awt.Color(183, 240, 240));
        analyzeButton1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(analyzeButton1, org.openide.util.NbBundle.getMessage(ProjectTopComp.class, "ProjectTopComp.analyzeButton1.text")); // NOI18N
        analyzeButton1.setAlignmentX(0.5F);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(16, 43, 13, 25);
        jPanel5.add(analyzeButton1, gridBagConstraints);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(0, 450, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(580, Short.MAX_VALUE))
        );

        add(jPanel1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    /**
     * 
     * @param evt starts function for loading model
     */
    private void addButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addButton1MouseClicked
        loadModel();
    }//GEN-LAST:event_addButton1MouseClicked

    /**
     * TEMP. behavior, remove button will be removing selected secondary face later
     * @param evt Removes primary face
     */
    private void removeButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeButton1MouseClicked
        if (this.project.getPrimaryFace() != null) {
            this.project.removePrimaryFace();
            jLabel1.setText("");   
        }
    }//GEN-LAST:event_removeButton1MouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton1;
    private javax.swing.JButton analyzeButton1;
    private javax.swing.JButton collapseButton1;
    private javax.swing.JButton deselectAllButton1;
    private javax.swing.JButton inflateButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JButton removeButton1;
    private javax.swing.JButton selectAllButton1;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
    
    /**
     * Loads model selected in file chooser by user
     */
    public void loadModel () {
        String[] extensions = new String[2];
        extensions[0] = "obj";
        extensions[1] = "OBJ";
        
        //enables to shows just .obj files in file chooser
        ModelFileFilter filter = new ModelFileFilter(extensions, "*.obj");
        JFileChooser jFileChooser1 = new JFileChooser(getPrefferedModelPath());
        jFileChooser1.setPreferredSize(new Dimension (800,500));
       
        jFileChooser1.addChoosableFileFilter(filter);        
       
        //file chooser will appear on top of projectTopComp
        jFileChooser1.showOpenDialog(this);
        jFileChooser1.setDialogTitle("Import obj file");
        
        setPrefferedModelPath(jFileChooser1.getCurrentDirectory().toString());
        
        File[] fileArray = new File[1];
        //saves selected file by user as first element in array
        fileArray[0] = jFileChooser1.getSelectedFile();

        if (fileArray.length <= 0) {
            System.out.print("No file chosen.");
        } else {
            this.addModel(fileArray[0]);
        }       
    }
    
    /**
     * Loads the model in .obj format from file and adds this model to project
     * as primary face. If file is not correct, shows dialog with message.
     *
     * @param file File from which model will be read
     */
    private void addModel (final File file) {
        try {
            HumanFace loadedFace;
            loadedFace = new HumanFace(new File (file.getPath()));
            this.project.setPrimaryFace(loadedFace);
            jLabel1.setText(file.getName());
            createSingleFaceTab(loadedFace, file.getName());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            JOptionPane.showMessageDialog(this, "File doesn't contain any model", "Model is not loaded.",
                    0, new ImageIcon(getClass().getResource("/notLoadedModel.png")));
            System.out.println ("File doesn't contain any model");
        }
    }
    
    private void setPrefferedModelPath(String s) {
        //TODO remove duplicate with PreferenceTopComponent
        try {
            FileWriter rewriter = new FileWriter("preferences.fip", false);
            rewriter.write(s);
            rewriter.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }   
    }
    
    private String getPrefferedModelPath() {
        //TODO remove duplicate with PreferenceTopComponent
        String data = "";
        try {
            File myObj = new File(/*propPath + */"preferences.fip");
            if (myObj.length() == 0)
                return data;
            try (Scanner myReader = new Scanner(myObj)) {
                data = myReader.nextLine();
            }            
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
        return data;
    }
    
    private void createSingleFaceTab(HumanFace face, String name) {
        CanvasTC newTab = new CanvasTC();
        newTab.setName(name);
        newTab.getCanvas().getScene().addDrawale(new Drawable(face.getMeshModel()));
        this.singleFaceTabs.put(face, newTab);
        newTab.open();
        newTab.requestActive();
        //newTab.getCanvas().getGLCanvas().display();
        //newTab.repaint();
        //newTab.getCanvas().getGLCanvas().setVisible(true);
    }

}
