/*
 * 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.core;

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.face.HumanFaceFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.openide.filesystems.FileChooserBuilder;

/**
 * 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, SingleFaceTab> singleFaceTabs = new HashMap<>();
    private Map<HumanFace, FaceToFaceTab> faceToFaceTabs = 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);
        analyzeButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                analyzeButton1MouseClicked(evt);
            }
        });
        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

    private void analyzeButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_analyzeButton1MouseClicked
        // TODO add your handling code here:
        loadTwoModels();
    }//GEN-LAST:event_analyzeButton1MouseClicked

    // 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 () {
        File file = new FileChooserBuilder(ProjectTopComp.class)
                .setTitle("Open human face(s)")
                .setDefaultWorkingDirectory(new File (System.getProperty("user.home")))
                //.setApproveText("Add")
                .setFileFilter(new FileNameExtensionFilter("obj files (*.obj)", "obj"))
                .setAcceptAllFileFilterUsed(true)
                .showOpenDialog();
        
        if (file== null) {
            System.out.print("No file chosen.");
        } else {
            String faceId = HumanFaceFactory.instance().loadFace(file);
            HumanFace face = HumanFaceFactory.instance().getFace(faceId);
            
            try {
                // simple hack:
                Path path = Paths.get(file.getAbsolutePath());
                Path folder = path.getParent();
                Path filename = path.getFileName();
                String filestr = filename.toString();
                filestr = filestr.split("_ECA.obj")[0];
                filestr = filestr + "_landmarks.csv";
                face.loadFeaturePoints(folder.toString(), filestr);
            } catch(IOException ex) {
                ex.printStackTrace();
            }
            
            this.project.setPrimaryFace(face);
            jLabel1.setText(face.getName());
            createSingleFaceTab(face, face.getName());
        } 
    }
    
    /**
     * Load two models for 1:1 comparison
     */
    public void loadTwoModels () {
        File file1 = new FileChooserBuilder(ProjectTopComp.class)
                .setTitle("Open human face(s)")
                .setDefaultWorkingDirectory(new File (System.getProperty("user.home")))
                //.setApproveText("Add")
                .setFileFilter(new FileNameExtensionFilter("obj files (*.obj)", "obj"))
                .setAcceptAllFileFilterUsed(true)
                .showOpenDialog();
        
        File file2 = new FileChooserBuilder(ProjectTopComp.class)
                .setTitle("Open human face(s)")
                .setDefaultWorkingDirectory(new File (System.getProperty("user.home")))
                //.setApproveText("Add")
                .setFileFilter(new FileNameExtensionFilter("obj files (*.obj)", "obj"))
                .setAcceptAllFileFilterUsed(true)
                .showOpenDialog();
        
        if (file1 == null || file2 == null) {
            System.out.print("Missing file.");
        } else {
            String faceId1 = HumanFaceFactory.instance().loadFace(file1);
            String faceId2 = HumanFaceFactory.instance().loadFace(file2);
            HumanFace face1 = HumanFaceFactory.instance().getFace(faceId1);
            HumanFace face2 = HumanFaceFactory.instance().getFace(faceId2);
            
            try {
                // simple hack:
                Path path = Paths.get(file1.getAbsolutePath());
                Path folder = path.getParent();
                Path filename = path.getFileName();
                String filestr = filename.toString();
                filestr = filestr.split("_ECA.obj")[0];
                filestr = filestr + "_landmarks.csv";
                face1.loadFeaturePoints(folder.toString(), filestr);
            } catch(IOException ex) {
                ex.printStackTrace();
            }
            
            try {
                // simple hack:
                Path path = Paths.get(file2.getAbsolutePath());
                Path folder = path.getParent();
                Path filename = path.getFileName();
                String filestr = filename.toString();
                filestr = filestr.split("_ECA.obj")[0];
                filestr = filestr + "_landmarks.csv";
                face2.loadFeaturePoints(folder.toString(), filestr);
            } catch(IOException ex) {
                ex.printStackTrace();
            }
            
            this.project.setPrimaryFace(face1);
            this.project.setSecondaryFaces(List.of(face2));
            jLabel1.setText(face1.getName());
            createFaceToFaceTab(face1, face2, "1:1");
        } 
    }
    
    private void createSingleFaceTab(HumanFace face, String name) {
        SingleFaceTab newTab = new SingleFaceTab(face, name);
        this.singleFaceTabs.put(face, newTab);
        newTab.open();
        newTab.requestActive();
    }

    private void createFaceToFaceTab(HumanFace face1, HumanFace face2, String name) {
        FaceToFaceTab newTab = new FaceToFaceTab(face1, face2, name);
        this.faceToFaceTabs.put(face1, newTab);
        this.faceToFaceTabs.put(face2, newTab);
        newTab.open();
        newTab.requestActive();
    }
}
