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

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.Timer;

/**
 *
 * @author Ronny
 */
public class MainFrame extends javax.swing.JFrame {
    //For chosing placement
    private static final int ASTEROID = 0;
    private static final int GEM = 1;
    private static final int PLAYER = 2;
    private static final int ENNEMY = 3;
    private static final int REMOVE = 4;
    
    private String filePath;
    private boolean isBuiltIn  = true;
    
    private int placementChoice = 4;
    public RealPlayer player;
    private int level = 1;
    private int maxLevels = 5;
    private Board board;
    private Timer repaintTimer;
    
    private boolean debugMode = false;
    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
        
        //Default load the first Level from the List
        BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/interactiveproject/spacesimulator/level/LevelList.txt")));
        String line = "";
        try {
            line = br.readLine();
        } catch (IOException ex) {
            System.err.println("Level Selection file damaged.");
        }
        
        board = new Board(line);
        filePath = line;
        player = board.player;
        this.repaintTimer = new Timer(300, repainter);
        repaintTimer.start();
        drawPanel.setBoard(board);
        if(!debugMode)
        {
            turnButton.setVisible(false);
            moveButton.setVisible(false);
            attackButton.setVisible(false);
            collectButton.setVisible(false);
        }
        //this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
    ActionListener repainter = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
          drawPanel.repaint();
          if(board.isOver())
          {
            repaintTimer.stop();
          }
        }
    };

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public void setIsBuiltIn(boolean isBuiltIn) {
        this.isBuiltIn = isBuiltIn;
    }
    
    
    public void reset()
    {
        board.reset(filePath,isBuiltIn);
        repaintTimer.start();
    }
    
    public void deselectAll()
    {
        playerButton.setSelected(false);
        ennemyButton.setSelected(false);
        gemButton.setSelected(false);
        asteroidButton.setSelected(false);
        removeButton.setSelected(false);
    }
    
    public Object getInterfaceObject()
    {
        return player;
    }
    /**
     * 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">                          
    private void initComponents() {

        drawPanel = new interactiveproject.spacesimulator.DrawPanel();
        menuBar = new javax.swing.JToolBar();
        jButton2 = new javax.swing.JButton();
        loadButton = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jToolBar2 = new javax.swing.JToolBar();
        collectButton = new javax.swing.JButton();
        turnButton = new javax.swing.JButton();
        moveButton = new javax.swing.JButton();
        attackButton = new javax.swing.JButton();
        resetButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jSlider1 = new javax.swing.JSlider();
        jToolBar3 = new javax.swing.JToolBar();
        ennemyButton = new javax.swing.JToggleButton();
        playerButton = new javax.swing.JToggleButton();
        gemButton = new javax.swing.JToggleButton();
        asteroidButton = new javax.swing.JToggleButton();
        removeButton = new javax.swing.JToggleButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Space Simulator");

        drawPanel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                drawPanelMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout drawPanelLayout = new javax.swing.GroupLayout(drawPanel);
        drawPanel.setLayout(drawPanelLayout);
        drawPanelLayout.setHorizontalGroup(
            drawPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 811, Short.MAX_VALUE)
        );
        drawPanelLayout.setVerticalGroup(
            drawPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 345, Short.MAX_VALUE)
        );

        menuBar.setRollover(true);

        jButton2.setText("Create New Level");
        jButton2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        menuBar.add(jButton2);

        loadButton.setText("Load Level");
        loadButton.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        loadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadButtonActionPerformed(evt);
            }
        });
        menuBar.add(loadButton);

        jButton3.setText("Save");
        jButton3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        menuBar.add(jButton3);

        jToolBar2.setRollover(true);

        collectButton.setText("collect");
        collectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                collectButtonActionPerformed(evt);
            }
        });
        jToolBar2.add(collectButton);

        turnButton.setText("turn");
        turnButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                turnButtonActionPerformed(evt);
            }
        });
        jToolBar2.add(turnButton);

        moveButton.setText("move");
        moveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                moveButtonActionPerformed(evt);
            }
        });
        jToolBar2.add(moveButton);

        attackButton.setText("attack");
        attackButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                attackButtonActionPerformed(evt);
            }
        });
        jToolBar2.add(attackButton);

        resetButton.setText("Reset");
        resetButton.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        resetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetButtonActionPerformed(evt);
            }
        });
        jToolBar2.add(resetButton);

        jLabel1.setText("Speed of Animation:");
        jToolBar2.add(jLabel1);

        jSlider1.setMinimum(10);
        jSlider1.setValue(0);
        jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSlider1StateChanged(evt);
            }
        });
        jToolBar2.add(jSlider1);

        jToolBar3.setRollover(true);

        ennemyButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/interactiveproject/spacesimulator/images/enemy_icon.png"))); // NOI18N
        ennemyButton.setFocusable(false);
        ennemyButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        ennemyButton.setMaximumSize(new java.awt.Dimension(29, 29));
        ennemyButton.setMinimumSize(new java.awt.Dimension(29, 29));
        ennemyButton.setPreferredSize(new java.awt.Dimension(29, 29));
        ennemyButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        ennemyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ennemyButtonActionPerformed(evt);
            }
        });
        jToolBar3.add(ennemyButton);

        playerButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/interactiveproject/spacesimulator/images/player_icon.png"))); // NOI18N
        playerButton.setFocusable(false);
        playerButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        playerButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        playerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playerButtonActionPerformed(evt);
            }
        });
        jToolBar3.add(playerButton);

        gemButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/interactiveproject/spacesimulator/images/gem_icon.png"))); // NOI18N
        gemButton.setFocusable(false);
        gemButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        gemButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        gemButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                gemButtonActionPerformed(evt);
            }
        });
        jToolBar3.add(gemButton);

        asteroidButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/interactiveproject/spacesimulator/images/wall_icon.png"))); // NOI18N
        asteroidButton.setFocusable(false);
        asteroidButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        asteroidButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        asteroidButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                asteroidButtonActionPerformed(evt);
            }
        });
        jToolBar3.add(asteroidButton);

        removeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/interactiveproject/spacesimulator/images/delete_icon.png"))); // NOI18N
        removeButton.setFocusable(false);
        removeButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        removeButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });
        jToolBar3.add(removeButton);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(drawPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(menuBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(72, 72, 72)
                        .addComponent(jToolBar3, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(menuBar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jToolBar3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(drawPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void turnButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        player.turnClockwise();
    }                                          

    private void attackButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        player.attack();
    }                                            

    private void moveButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        player.moveForward();
    }                                          

    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        reset();
    }                                           

    private void collectButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
        player.collect();
    }                                             

    private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        reset();
        LevelSelectDialog dialog = new LevelSelectDialog(this, rootPaneCheckingEnabled, board, this);
        dialog.setVisible(true);
    }                                          

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        NewLevelDialog dialog = new NewLevelDialog(this, rootPaneCheckingEnabled, board);
        dialog.setVisible(true);
    }                                        

    private void drawPanelMouseClicked(java.awt.event.MouseEvent evt) {                                       
       if(placementChoice == ASTEROID)
           board.placeAsteroid(evt.getX(), evt.getY());
       else if(placementChoice == PLAYER)
           board.placePlayer(evt.getX(), evt.getY());
       else if(placementChoice == GEM)
           board.placeGem(evt.getX(), evt.getY());
       else if(placementChoice == ENNEMY)
           board.placeEnnemy(evt.getX(), evt.getY());
       else if(placementChoice == REMOVE)
           board.remove(evt.getX(), evt.getY());
    }                                      

    private void ennemyButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        placementChoice = ENNEMY;
        deselectAll();
        ennemyButton.setSelected(true);
    }                                            

    private void playerButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        placementChoice = PLAYER;
        deselectAll();
        playerButton.setSelected(true);
    }                                            

    private void gemButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
        placementChoice = GEM;
        deselectAll();
        gemButton.setSelected(true);
    }                                         

    private void asteroidButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
        placementChoice = ASTEROID;
        deselectAll();
        asteroidButton.setSelected(true);
    }                                              

    private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {                                      
        player.setSpeed(jSlider1.getValue());
    }                                     

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        OpenLevelDialog fileChooser = new OpenLevelDialog();
        int selection = fileChooser.showSaveDialog(this);
        if(selection == OpenLevelDialog.APPROVE_OPTION)
        {
            board.saveToFile(fileChooser.getSelectedFile().getAbsolutePath().toString());
        }
    }                                        

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        placementChoice = REMOVE;
        deselectAll();
        removeButton.setSelected(true);
    }                                            

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JToggleButton asteroidButton;
    private javax.swing.JButton attackButton;
    private javax.swing.JButton collectButton;
    private interactiveproject.spacesimulator.DrawPanel drawPanel;
    private javax.swing.JToggleButton ennemyButton;
    private javax.swing.JToggleButton gemButton;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JSlider jSlider1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JToolBar jToolBar3;
    private javax.swing.JButton loadButton;
    private javax.swing.JToolBar menuBar;
    private javax.swing.JButton moveButton;
    private javax.swing.JToggleButton playerButton;
    private javax.swing.JToggleButton removeButton;
    private javax.swing.JButton resetButton;
    private javax.swing.JButton turnButton;
    // End of variables declaration                   
}
