/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.nplusc.izc.TWPUtil;

import de.nplusc.izc.tools.IOtools.iZformats.IZTile;
import de.nplusc.izc.tools.UiToolz.UiTools;
import de.nplusc.izc.tools.baseTools.Tools;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.DefaultListModel;

/**
 *
 * @author LH
 */
public class OpenGUI extends javax.swing.JFrame
{
    TileRegistry r;
    /**
     * Creates new form OpenGUI
     */
    public OpenGUI()
    {
        r=new TileRegistry(Tools.processEnvVarsinLine("%appdata%\\iZTiler\\persistentData\\TileReg"));
        initComponents();
        reloadTlist();
    }

    /**
     * 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")
    boolean SizeFinalized = false;
    
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        sbUpDown = new javax.swing.JScrollBar();
        sbLEftRight = new javax.swing.JScrollBar();
        pnlViewPort = new javax.swing.JPanel();
        init = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        txfBreite = new javax.swing.JTextField();
        txfHöhe = new javax.swing.JTextField();
        jSeparator3 = new javax.swing.JSeparator();
        pbarProgress = new javax.swing.JProgressBar();
        lblStatus = new javax.swing.JLabel();
        createTiler = new javax.swing.JButton();
        regTile = new javax.swing.JButton();
        pnlLSPV = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstTilesOfPrj = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        sbUpDown.addAdjustmentListener(new java.awt.event.AdjustmentListener()
        {
            public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt)
            {
                sbUpDownAdjustmentValueChanged(evt);
            }
        });

        sbLEftRight.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
        sbLEftRight.addAdjustmentListener(new java.awt.event.AdjustmentListener()
        {
            public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt)
            {
                sbLEftRightAdjustmentValueChanged(evt);
            }
        });

        pnlViewPort.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mousePressed(java.awt.event.MouseEvent evt)
            {
                pnlViewPortMousePressed(evt);
            }
        });

        javax.swing.GroupLayout pnlViewPortLayout = new javax.swing.GroupLayout(pnlViewPort);
        pnlViewPort.setLayout(pnlViewPortLayout);
        pnlViewPortLayout.setHorizontalGroup(
            pnlViewPortLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        pnlViewPortLayout.setVerticalGroup(
            pnlViewPortLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 418, Short.MAX_VALUE)
        );

        init.setText("Initialisieren");
        init.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                initActionPerformed(evt);
            }
        });

        jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);

        txfBreite.setEditable(false);
        txfBreite.setText("Breite");
        txfBreite.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mousePressed(java.awt.event.MouseEvent evt)
            {
                txfBreiteMousePressed(evt);
            }
        });
        txfBreite.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                txfBreiteActionPerformed(evt);
            }
        });

        txfHöhe.setEditable(false);
        txfHöhe.setText("Höhe");
        txfHöhe.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mousePressed(java.awt.event.MouseEvent evt)
            {
                txfHöheMousePressed(evt);
            }
        });

        lblStatus.setText("Status");

        createTiler.setText("Tile erzeugen");
        createTiler.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                createTilerActionPerformed(evt);
            }
        });

        regTile.setText("Tile registrieren+");
        regTile.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                regTileActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlLSPVLayout = new javax.swing.GroupLayout(pnlLSPV);
        pnlLSPV.setLayout(pnlLSPVLayout);
        pnlLSPVLayout.setHorizontalGroup(
            pnlLSPVLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 228, Short.MAX_VALUE)
        );
        pnlLSPVLayout.setVerticalGroup(
            pnlLSPVLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 262, Short.MAX_VALUE)
        );

        lstTilesOfPrj.setModel(new javax.swing.DefaultListModel<String>()
        );
        lstTilesOfPrj.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mousePressed(java.awt.event.MouseEvent evt)
            {
                lstTilesOfPrjMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(lstTilesOfPrj);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(sbLEftRight, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 677, Short.MAX_VALUE)
                    .addComponent(pnlViewPort, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sbUpDown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator1)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(txfBreite, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(txfHöhe, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(init, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(regTile, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(createTiler, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(28, 28, 28))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(pnlLSPV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
            .addComponent(pbarProgress, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblStatus, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jSeparator3))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txfBreite, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txfHöhe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(init)
                        .addGap(25, 25, 25)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(createTiler)
                            .addComponent(regTile))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(pnlLSPV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 439, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(sbUpDown, javax.swing.GroupLayout.PREFERRED_SIZE, 418, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(pnlViewPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(sbLEftRight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addComponent(lblStatus)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pbarProgress, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

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

    private void txfBreiteMousePressed(java.awt.event.MouseEvent evt)//GEN-FIRST:event_txfBreiteMousePressed
    {//GEN-HEADEREND:event_txfBreiteMousePressed
        if(SizeFinalized)
            return;
        int s = Tools.numberInputWIndow(4, new int[]{-1});
        if(s>0)
        {
        txfBreite.setText(""+s);
        }
    }//GEN-LAST:event_txfBreiteMousePressed

    private void txfBreiteActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_txfBreiteActionPerformed
    {//GEN-HEADEREND:event_txfBreiteActionPerformed

    }//GEN-LAST:event_txfBreiteActionPerformed

    private void txfHöheMousePressed(java.awt.event.MouseEvent evt)//GEN-FIRST:event_txfHöheMousePressed
    {//GEN-HEADEREND:event_txfHöheMousePressed
        if(SizeFinalized)
        return;
        int s = Tools.numberInputWIndow(4, new int[]{-1});
        if(s>0)
        {
        txfHöhe.setText(""+s);
        }
    }//GEN-LAST:event_txfHöheMousePressed

    
    BufferedImage Overlay;
    TileAttrib[][][] tileWorkArea;
    private void initActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_initActionPerformed
    {//GEN-HEADEREND:event_initActionPerformed
        new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                IZTile gridUnit = new IZTile("D:\\srcs\\iztt\\GridUnit.iZtile");
                Image grid = gridUnit.getThumb();
                int height = Integer.valueOf(txfHöhe.getText());
                int width = Integer.valueOf(txfBreite.getText());
                int prg = 0;
                int Tiles = height*width;
                pbarProgress.setMinimum(0);
                pbarProgress.setMaximum(Tiles);
                lblStatus.setText("Erzeuge Gitternetz");
                tileWorkArea = new TileAttrib[width][height][];
                BufferedImage img = new BufferedImage(width*50, height*50, BufferedImage.TYPE_INT_ARGB);
                Graphics2D painter = img.createGraphics();
                for (int i = 0; i < width; i++)
                {
                    for (int j = 0; j < height; j++)
                    {
                        painter.drawImage(grid, i*50, j*50, null);
                        prg++;
                        TileAttrib[] layers = new TileAttrib[100];
                        for (int k = 0; k < 100; k++)
                        {
                            layers[i] = new TileAttrib();
                        }
                        tileWorkArea[i][j] = layers;
                        
                        if(prg%10==0)
                        {
                            pbarProgress.setValue(prg);
                        }
                    }
                }
                Overlay = img;
                
                int vpHeight = pnlViewPort.getHeight();
                int vpWidth = pnlViewPort.getWidth();
                sbUpDown.setMinimum(0);
                sbUpDown.setMaximum(height*50-vpHeight);
                sbLEftRight.setMinimum(0);
                sbLEftRight.setMaximum(width*50-vpWidth);
                sbUpDown.setValue(0);
                sbLEftRight.setValue(0);
                redraw();
                lblStatus.setText("Bereit");
            }
            
        }).start();
    }//GEN-LAST:event_initActionPerformed

    private void redraw()
    {
        int vpHeight = pnlViewPort.getHeight();
        int vpWidth = pnlViewPort.getWidth();
        int x =  sbLEftRight.getValue();
        int y = sbUpDown.getValue();
        Image viewGrid = Overlay.getSubimage(x, y, vpWidth, vpHeight);
        Graphics2D pa = (Graphics2D) pnlViewPort.getGraphics();
        pa.clearRect(0, 0, vpWidth, vpHeight);
        pa.drawImage(viewGrid, 0, 0, null);
        
    }
           
    
    
    
    private void sbUpDownAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt)//GEN-FIRST:event_sbUpDownAdjustmentValueChanged
    {//GEN-HEADEREND:event_sbUpDownAdjustmentValueChanged
        redraw();
    }//GEN-LAST:event_sbUpDownAdjustmentValueChanged

    private void sbLEftRightAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt)//GEN-FIRST:event_sbLEftRightAdjustmentValueChanged
    {//GEN-HEADEREND:event_sbLEftRightAdjustmentValueChanged
        redraw();
    }//GEN-LAST:event_sbLEftRightAdjustmentValueChanged

    private void createTilerActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_createTilerActionPerformed
    {//GEN-HEADEREND:event_createTilerActionPerformed
        new TileImporter(r).setVisible(true);
    }//GEN-LAST:event_createTilerActionPerformed

    private void regTileActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_regTileActionPerformed
    {//GEN-HEADEREND:event_regTileActionPerformed
        String tpath = Tools.FileChooseDlg(this, true, false, new String[]{"iZtile"});
        r.addTile(tpath, Tools.getInputString("Name"),true);
        reloadTlist();
    }//GEN-LAST:event_regTileActionPerformed

    private void lstTilesOfPrjMousePressed(java.awt.event.MouseEvent evt)//GEN-FIRST:event_lstTilesOfPrjMousePressed
    {//GEN-HEADEREND:event_lstTilesOfPrjMousePressed
        DefaultListModel<String> lm = (DefaultListModel<String>) lstTilesOfPrj.getModel();
        String tn = lm.get(lstTilesOfPrj.getSelectedIndex());
        IZTile t = r.getTile(tn);
        UiTools.ScaleImageIntoFrame(t.getThumbPath(), (Graphics2D) pnlLSPV.getGraphics(), pnlLSPV.getHeight(), pnlLSPV.getWidth(), true);
    }//GEN-LAST:event_lstTilesOfPrjMousePressed

    private void pnlViewPortMousePressed(java.awt.event.MouseEvent evt)//GEN-FIRST:event_pnlViewPortMousePressed
    {//GEN-HEADEREND:event_pnlViewPortMousePressed
        int w = evt.getX();
        int h = evt.getY();
        int offsX = sbLEftRight.getValue();
        int offsY = sbUpDown.getValue();
        boolean add = Tools.dlg(true, "Tile Hinzufügen oder bearbeiten?", "", "Hinzufügen", "Bearbeiten");
        int tX = (w+offsX)&50;
        int tY = (h+offsY)%50;
        if(add)
        {
            DefaultListModel<String> lm = (DefaultListModel<String>) lstTilesOfPrj.getModel();
            String tn = lm.get(lstTilesOfPrj.getSelectedIndex());
            IZTile t = r.getTile(tn);
            if(tileWorkArea[tX][tY][0].getTopmostOccupier()==-1)
            {
                tileWorkArea[tX][tY][0].setHeight(t.getHeightInTiles());
                tileWorkArea[tX][tY][0].setWidth(t.getWidthInTiles());
                
            }
        }
    }//GEN-LAST:event_pnlViewPortMousePressed

    
    
    private void reloadTlist()
    {
        DefaultListModel<String> lm = (DefaultListModel<String>) lstTilesOfPrj.getModel();
        lm.clear();
        String[] tiles = r.getNames();
        for (String tileid : tiles)
        {
            lm.addElement(tileid);
        }
    }
    
    
    
    /**
     * @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(OpenGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(OpenGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(OpenGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(OpenGUI.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 OpenGUI().setVisible(true);
            }
        });
        
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton createTiler;
    private javax.swing.JButton init;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JLabel lblStatus;
    private javax.swing.JList lstTilesOfPrj;
    private javax.swing.JProgressBar pbarProgress;
    private javax.swing.JPanel pnlLSPV;
    private javax.swing.JPanel pnlViewPort;
    private javax.swing.JButton regTile;
    private javax.swing.JScrollBar sbLEftRight;
    private javax.swing.JScrollBar sbUpDown;
    private javax.swing.JTextField txfBreite;
    private javax.swing.JTextField txfHöhe;
    // End of variables declaration//GEN-END:variables
}
