/*
 * Copyright 2014 - 2017 Cognizant Technology Solutions
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cognizant.cognizantits.ide.main.ui;

import com.cognizant.cognizantits.datalib.testdata.TestDataFactory;
import com.cognizant.cognizantits.ide.main.mainui.AppMainFrame;
import com.cognizant.cognizantits.ide.main.utils.CognizantITSFileChooser;
import com.cognizant.cognizantits.ide.main.utils.recentItem.RecentItem;
import com.cognizant.cognizantits.ide.settings.AppSettings;
import com.cognizant.cognizantits.ide.util.Validator;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.io.File;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JToggleButton;

/**
 *
 *
 */
public class StartUp extends javax.swing.JDialog {

    AppMainFrame sMainFrame;
    DefaultListModel recentModel;

    private Boolean recentChanged = false;

    public StartUp(AppMainFrame sMainFrame) {
        super(new JFrame());
        this.sMainFrame = sMainFrame;
        initComponents();
        setIconImage(new ImageIcon(getClass().getResource("/ui/resources/favicon.png")).getImage());
        initFileChooser();
        load();
    }

    public void showIt() {
        setSize(600, 400);
        sMainFrame.setVisible(false);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void initFileChooser() {
        systemPanel.add(CognizantITSFileChooser.OPEN_PROJECT, BorderLayout.CENTER);
        CognizantITSFileChooser.OPEN_PROJECT.afterFileSelected = this::loadProject;
    }

    private void load() {
        loadRecent();
        loadAppProjects();
        testDataType.setModel(new DefaultComboBoxModel(TestDataFactory.getDATA_PROVIDER_NAMES().toArray()));
        projLocation.setCaretPosition(0);
        openLastOpened.setSelected(AppSettings.canOpenRecentProjects());
        recentChanged = false;
    }

    private void loadRecent() {
        recentModel = new DefaultListModel();
        for (RecentItem recentItem : sMainFrame.getRecentItems().getRECENT_ITEMS()) {
            recentModel.addElement(recentItem);
        }
        recentItems.setModel(recentModel);
        if (recentModel.isEmpty()) {
            recentToggle.setEnabled(false);
            recentToggle.setForeground(Color.GRAY);
            appToggle.setSelected(true);
        } else {
            recentItems.setSelectedIndex(0);
            recentToggle.setSelected(true);
        }

    }

    private void loadAppProjects() {
        DefaultListModel projModel = new DefaultListModel();
        File projects = new File("Projects");
        if (projects.exists()) {
            for (File project : projects.listFiles()) {
                if (project.isDirectory()) {
                    File[] file = project.listFiles((dir1, name) -> name.endsWith(".project"));
                    if (file.length > 0) {
                        projModel.addElement(project.getName());
                    }
                }
            }
            appItems.setSelectedIndex(0);
        }
        appItems.setModel(projModel);
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        testDataTypeLabel = new javax.swing.JLabel();
        testDataType = new javax.swing.JComboBox<>();
        jToolBar1 = new javax.swing.JToolBar();
        recentToggle = new javax.swing.JToggleButton();
        appToggle = new javax.swing.JToggleButton();
        jToggleButton3 = new javax.swing.JToggleButton();
        jToggleButton4 = new javax.swing.JToggleButton();
        cardPanel = new javax.swing.JPanel();
        recentPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        recentItems = new javax.swing.JList<>();
        appPanel = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        appItems = new javax.swing.JList<>();
        systemPanel = new javax.swing.JPanel();
        newProjPanel = new javax.swing.JPanel();
        error = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        projName = new javax.swing.JTextField();
        projLocation = new javax.swing.JTextField();
        browseProject = new javax.swing.JButton();
        createNewProject = new javax.swing.JButton();
        jToolBar2 = new javax.swing.JToolBar();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767));
        openLastOpened = new javax.swing.JCheckBox();
        filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(5, 0), new java.awt.Dimension(5, 0), new java.awt.Dimension(5, 32767));

        testDataTypeLabel.setText("Testdata Type");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Start Up Screen");
        setAlwaysOnTop(true);
        setModal(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jToolBar1.setFloatable(false);
        jToolBar1.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jToolBar1.setRollover(true);

        buttonGroup1.add(recentToggle);
        recentToggle.setText("Recent");
        recentToggle.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        recentToggle.setFocusable(false);
        recentToggle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        recentToggle.setPreferredSize(new java.awt.Dimension(75, 50));
        recentToggle.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        recentToggle.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                recentToggleItemStateChanged(evt);
            }
        });
        jToolBar1.add(recentToggle);

        buttonGroup1.add(appToggle);
        appToggle.setText("Application");
        appToggle.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        appToggle.setFocusable(false);
        appToggle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        appToggle.setPreferredSize(new java.awt.Dimension(75, 50));
        appToggle.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        appToggle.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                appToggleItemStateChanged(evt);
            }
        });
        jToolBar1.add(appToggle);

        buttonGroup1.add(jToggleButton3);
        jToggleButton3.setText("System");
        jToggleButton3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jToggleButton3.setFocusable(false);
        jToggleButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jToggleButton3.setPreferredSize(new java.awt.Dimension(75, 50));
        jToggleButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToggleButton3.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jToggleButton3ItemStateChanged(evt);
            }
        });
        jToolBar1.add(jToggleButton3);

        buttonGroup1.add(jToggleButton4);
        jToggleButton4.setText("New");
        jToggleButton4.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jToggleButton4.setFocusable(false);
        jToggleButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jToggleButton4.setPreferredSize(new java.awt.Dimension(75, 50));
        jToggleButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToggleButton4.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jToggleButton4ItemStateChanged(evt);
            }
        });
        jToolBar1.add(jToggleButton4);

        getContentPane().add(jToolBar1, java.awt.BorderLayout.WEST);

        cardPanel.setLayout(new java.awt.CardLayout());

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

        recentItems.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        recentItems.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                recentItemsMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(recentItems);

        recentPanel.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        cardPanel.add(recentPanel, "Recent");

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

        appItems.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        appItems.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                appItemsMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(appItems);

        appPanel.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        cardPanel.add(appPanel, "Application");

        systemPanel.setLayout(new java.awt.BorderLayout());
        cardPanel.add(systemPanel, "System");

        error.setForeground(java.awt.Color.blue);

        jLabel1.setText("Project Name");

        jLabel2.setText("Project Location");

        projName.setText("Project Name");
        projName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                projNameActionPerformed(evt);
            }
        });

        projLocation.setText(new File("Projects").getAbsolutePath());

        browseProject.setText("...");
        browseProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseProjectActionPerformed(evt);
            }
        });

        createNewProject.setText("Create New Project");
        createNewProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createNewProjectActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout newProjPanelLayout = new javax.swing.GroupLayout(newProjPanel);
        newProjPanel.setLayout(newProjPanelLayout);
        newProjPanelLayout.setHorizontalGroup(
            newProjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(newProjPanelLayout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(newProjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(newProjPanelLayout.createSequentialGroup()
                        .addGroup(newProjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(error))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(newProjPanelLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
            .addGroup(newProjPanelLayout.createSequentialGroup()
                .addContainerGap(65, Short.MAX_VALUE)
                .addGroup(newProjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(projLocation, javax.swing.GroupLayout.PREFERRED_SIZE, 407, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(projName, javax.swing.GroupLayout.PREFERRED_SIZE, 407, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(browseProject)
                .addGap(0, 16, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, newProjPanelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(createNewProject)
                .addGap(189, 189, 189))
        );
        newProjPanelLayout.setVerticalGroup(
            newProjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(newProjPanelLayout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(error)
                .addGap(21, 21, 21)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(projName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addComponent(jLabel2)
                .addGap(21, 21, 21)
                .addGroup(newProjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(projLocation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(browseProject))
                .addGap(40, 40, 40)
                .addComponent(createNewProject)
                .addContainerGap(41, Short.MAX_VALUE))
        );

        cardPanel.add(newProjPanel, "New");

        getContentPane().add(cardPanel, java.awt.BorderLayout.CENTER);

        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);
        jToolBar2.setMinimumSize(new java.awt.Dimension(233, 40));
        jToolBar2.setPreferredSize(new java.awt.Dimension(100, 40));
        jToolBar2.add(filler1);

        openLastOpened.setText("Always Open the Last Opened Project");
        openLastOpened.setToolTipText("You can change this setting on File-> Configuration-> Options");
        openLastOpened.setFocusable(false);
        openLastOpened.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        openLastOpened.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                openLastOpenedItemStateChanged(evt);
            }
        });
        jToolBar2.add(openLastOpened);
        jToolBar2.add(filler2);

        getContentPane().add(jToolBar2, java.awt.BorderLayout.NORTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void recentToggleItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_recentToggleItemStateChanged
        toggleView(evt);
        setTitle("Open Recent Project");
    }//GEN-LAST:event_recentToggleItemStateChanged

    private void appToggleItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_appToggleItemStateChanged
        toggleView(evt);
        setTitle("Open Project's in Application Location");
    }//GEN-LAST:event_appToggleItemStateChanged

    private void jToggleButton3ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jToggleButton3ItemStateChanged
        toggleView(evt);
        setTitle("Open Project from System");
    }//GEN-LAST:event_jToggleButton3ItemStateChanged

    private void jToggleButton4ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jToggleButton4ItemStateChanged
        toggleView(evt);
        setTitle("Create a New Project");
        projName.requestFocusInWindow();
    }//GEN-LAST:event_jToggleButton4ItemStateChanged

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        sMainFrame.quit();
    }//GEN-LAST:event_formWindowClosing

    private void recentItemsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_recentItemsMouseClicked
        if (evt.getClickCount() == 2) {
            int index = recentItems.locationToIndex(evt.getPoint());
            if (index != -1) {
                loadProject(((RecentItem) recentModel.
                        getElementAt(index)).getLocation());
            }
        }
    }//GEN-LAST:event_recentItemsMouseClicked

    private void appItemsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_appItemsMouseClicked
        if (evt.getClickCount() == 2) {
            int index = appItems.locationToIndex(evt.getPoint());
            if (index != -1) {
                loadProject(new File("Projects" + File.separator
                        + appItems.getSelectedValue()).getAbsolutePath());
            }
        }
    }//GEN-LAST:event_appItemsMouseClicked

    private void openLastOpenedItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_openLastOpenedItemStateChanged
        AppSettings.openRecentProjectsOnLaunch(evt.getStateChange() == ItemEvent.SELECTED);
        recentChanged = true;
    }//GEN-LAST:event_openLastOpenedItemStateChanged

    private void browseProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseProjectActionPerformed
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int val = chooser.showOpenDialog(this);
        if (val == JFileChooser.APPROVE_OPTION) {
            projLocation.setText(chooser.getSelectedFile().getAbsolutePath());
        }
    }//GEN-LAST:event_browseProjectActionPerformed

    private void createNewProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createNewProjectActionPerformed
        if (Validator.isValidName(projName.getText().trim())) {
            String location;
            if (projLocation.getText().trim().isEmpty()) {
                location = System.getProperty("user.dir") + File.separator + "Projects";
            } else {
                location = projLocation.getText().trim();
            }
            createProject(location);
        } else {
            error.setText("Invalid Project Name");
        }
    }//GEN-LAST:event_createNewProjectActionPerformed

    private void projNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_projNameActionPerformed
        createNewProject.doClick();
    }//GEN-LAST:event_projNameActionPerformed

    private void createProject(String location) {
        File file = new File(location + File.separator + projName.getText());
        if (!file.exists()) {
            if (recentChanged) {
                AppSettings.store("Options Changed");
            }
            sMainFrame.createProject(projName.getText().trim(),
                    location,
                    testDataType.getSelectedItem().toString());
            closeWindow();
            sMainFrame.adjustUI();
            sMainFrame.setVisible(true);
        } else {
            error.setText("Project Location is not Empty / Project already present in the location");
        }
    }

    private void loadProject(String location) {
        if (new File(location).exists()) {
            sMainFrame.loadProject(location);
            closeWindow();
            sMainFrame.adjustUI();
            sMainFrame.setVisible(true);
            if (recentChanged) {
                AppSettings.store("Options Changed");
            }
        }
    }

    private void closeWindow() {
        CognizantITSFileChooser.OPEN_PROJECT.afterFileSelected = null;        
        setVisible(false);
    }

    private void toggleView(java.awt.event.ItemEvent evt) {
        JToggleButton toggleButton = ((JToggleButton) evt.getSource());
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            toggleButton.setFont(toggleButton.getFont().deriveFont(Font.BOLD));
            String text = toggleButton.getText();
            CardLayout layout = (CardLayout) cardPanel.getLayout();
            layout.show(cardPanel, text);
        } else {
            toggleButton.setFont(toggleButton.getFont().deriveFont(Font.PLAIN));
        }
    }

    private void onFileChooserApprove() {
//        if (jFileChooser1.getFileFilter().accept(jFileChooser1.getSelectedFile())) {
//            loadProject(jFileChooser1.getSelectedFile().getParentFile().getAbsolutePath());
//        }
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList<String> appItems;
    private javax.swing.JPanel appPanel;
    private javax.swing.JToggleButton appToggle;
    private javax.swing.JButton browseProject;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JPanel cardPanel;
    private javax.swing.JButton createNewProject;
    private javax.swing.JLabel error;
    private javax.swing.Box.Filler filler1;
    private javax.swing.Box.Filler filler2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToggleButton jToggleButton3;
    private javax.swing.JToggleButton jToggleButton4;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JPanel newProjPanel;
    private javax.swing.JCheckBox openLastOpened;
    private javax.swing.JTextField projLocation;
    private javax.swing.JTextField projName;
    private javax.swing.JList<String> recentItems;
    private javax.swing.JPanel recentPanel;
    private javax.swing.JToggleButton recentToggle;
    private javax.swing.JPanel systemPanel;
    private javax.swing.JComboBox<String> testDataType;
    private javax.swing.JLabel testDataTypeLabel;
    // End of variables declaration//GEN-END:variables
}