
import java.io.*;
import javax.swing.SpinnerNumberModel;


/**
 *
 * @author Jiri Stepanovsky
 */
public class Main extends javax.swing.JFrame {

    SpinnerNumberModel sm1 = new SpinnerNumberModel(5,1,80,1);
    SpinnerNumberModel sm2 = new SpinnerNumberModel(5,1,80,1);
    private CanvasPanel cp;
    private File file;
    public byte[][] map;
    public int width, heigth;
    public boolean editb = false;
    
    public Main() {
        if(cp == null){
            //app initialize
            cp = new CanvasPanel(this);
        }
        initComponents();
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        inputFileUrl = new javax.swing.JTextField();
        label = new javax.swing.JLabel();
        open = new javax.swing.JButton();
        canvasPanel = cp;
        outputLabel = new javax.swing.JLabel();
        next = new javax.swing.JButton();
        previous = new javax.swing.JButton();
        Exit = new javax.swing.JButton();
        edit = new javax.swing.JButton();
        newPanel = new javax.swing.JButton();
        progres = new javax.swing.JLabel();
        save = new javax.swing.JButton();
        S1 = new javax.swing.JSpinner(sm1);
        S2 = new javax.swing.JSpinner(sm2);

        jButton1.setText("jButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Bílá Paní");
        setResizable(false);

        inputFileUrl.setText("C:\\\\");
            inputFileUrl.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    inputFileUrlActionPerformed(evt);
                }
            });

            label.setText("File:");

            open.setText("Open");
            open.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    openActionPerformed(evt);
                }
            });

            canvasPanel.setBackground(new java.awt.Color(255, 255, 255));
            canvasPanel.setPreferredSize(new java.awt.Dimension(400, 400));

            outputLabel.setText("Open File");

            next.setText(">");
            next.setEnabled(false);
            next.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    nextActionPerformed(evt);
                }
            });

            previous.setText("<");
            previous.setEnabled(false);
            previous.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    previousActionPerformed(evt);
                }
            });

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

            edit.setText("Edit");
            edit.setEnabled(false);
            edit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    editActionPerformed(evt);
                }
            });

            newPanel.setText("New");
            newPanel.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    newPanelActionPerformed(evt);
                }
            });

            progres.setText("0/0");

            save.setText("Save");
            save.setEnabled(false);
            save.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    saveActionPerformed(evt);
                }
            });

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(outputLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(progres, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(previous)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(next))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(label)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(inputFileUrl))
                        .addComponent(canvasPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(Exit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(open, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(edit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(newPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(save, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(S1, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(S2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(label)
                        .addComponent(inputFileUrl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(open))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(canvasPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(S1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(S2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(newPanel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(edit)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(save)))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(outputLabel)
                        .addComponent(next)
                        .addComponent(previous)
                        .addComponent(Exit)
                        .addComponent(progres))
                    .addContainerGap())
            );

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

    private void inputFileUrlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputFileUrlActionPerformed
        openFile(inputFileUrl.getText());
    }//GEN-LAST:event_inputFileUrlActionPerformed

    private void openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed
        //Otevre prohlizec souboru
        javax.swing.JFileChooser fc = new javax.swing.JFileChooser(file);
        fc.showDialog(this, "Open file");
        File f = fc.getSelectedFile();
        if(f != null){
            openFile(f.toString());
        }
    }//GEN-LAST:event_openActionPerformed

    private void newPanelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newPanelActionPerformed
        width = ((Integer)S1.getValue()).intValue();
        heigth = ((Integer)S2.getValue()).intValue();
        map = null;
        map = new byte[width][heigth];
        map[0][0] = 2;
        map[width-1][heigth-1] = 3;
        cp.repaint();
        edit.setEnabled(true);
        save.setEnabled(true);
        editb = false;
        outputLabel.setText("New panel");
    }//GEN-LAST:event_newPanelActionPerformed

    private void editActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editActionPerformed
        editb = true;
        outputLabel.setText("Editing...");
    }//GEN-LAST:event_editActionPerformed

    private void previousActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousActionPerformed
        
    }//GEN-LAST:event_previousActionPerformed

    private void nextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextActionPerformed
        
    }//GEN-LAST:event_nextActionPerformed

    private void ExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitActionPerformed
        System.exit(0);
    }//GEN-LAST:event_ExitActionPerformed

    private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
       int i = 1;
        file = new File("./map.txt");
        while(file.exists()){
            file = null;
            file = new File("/map"+i+".txt");
            i++;
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            String s = width+" "+heigth+"\r\n";
            int x = 0, y = 0;
            while(y < heigth){
                if(map[x][y] == 2 ){
                    s+="&";
                    x++;
                }else if(map[x][y] == 3){
                    s+="#";
                    x++;
                }else if(map[x][y] == 1){
                    s+="X";
                    x++;
                }else if(map[x][y] == 0){
                    s+=".";
                    x++;
                }else if(map[x][y] == 4){
                    s+="@";
                    x++;
                }
                if(x >= width){
                    s+="\r\n";
                    x = 0;
                    y++;
                }
            }
            new PrintStream(fos).print(s);
            fos.close();
        } catch (Exception e) {
        }
        editb = false;
        outputLabel.setText("File has saved.");
    }//GEN-LAST:event_saveActionPerformed

    /**
     * @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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Exit;
    private javax.swing.JSpinner S1;
    private javax.swing.JSpinner S2;
    private java.awt.Canvas canvasPanel;
    private javax.swing.JButton edit;
    private javax.swing.JTextField inputFileUrl;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel label;
    private javax.swing.JButton newPanel;
    private javax.swing.JButton next;
    private javax.swing.JButton open;
    private javax.swing.JLabel outputLabel;
    private javax.swing.JButton previous;
    private javax.swing.JLabel progres;
    private javax.swing.JButton save;
    // End of variables declaration//GEN-END:variables

    private void openFile(String url){
        //pokusi se o otevreni a o precteni souboru
        FileInputStream fis;
        DataInputStream dis;
        try{
            file = new File(url);
            fis = new FileInputStream(file);
            dis = new DataInputStream(fis);
            //precteni sirky a vysky
            width = dis.read()-48;
            int i = dis.read();
            if(i == 10 || i == 32){
                i = dis.read();
            }else{
                width = (width*10)+i-48;
                dis.read();
                i = dis.read();
            }
            heigth = i-48;
            i = dis.read();
            if(i > 47 && i < 58){
                heigth = (heigth*10)+i-48;
                i = dis.read();
            }
            //vytvoreni pole o width a heigth
            map = null;
            map = new byte[width][heigth];
            int x1 = 0 , y1 = 0; //width , heigth
            //precteni zbytku mapy
            while(i > -1 && y1 < heigth){
                if(i == '&'){
                    //White Women
                    map[x1][y1] = 2;
                    x1++;
                }else if(i == '#'){
                    //TV
                    map[x1][y1] = 3;
                    x1++;
                }else if(i == 'X'){
                    //Wall
                    map[x1][y1] = 1;
                    x1++;
                }else if(i == '.'){
                    //nothing
                    map[x1][y1] = 0;
                    x1++;
                }else if(i == '@'){
                    //badman
                    map[x1][y1] = 4;
                    x1++;
                }
                if(x1 >= width){
                    x1 = 0;
                    y1++;
                }
                i = dis.read();
            }
            cp.repaint();
            outputLabel.setText("File is open");
            inputFileUrl.setText(file.toString());
            fis.close();
            dis.close();
            edit.setEnabled(true);
        }catch(Exception e){
            outputLabel.setText("File is Incorrect, please open file");
            edit.setEnabled(false);
        }
        save.setEnabled(true);
        editb = false;
    }
    
    

   
}