/*
 * 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 MapConverter;

import MapConverter.Serializables.GuadmazXml;
import MapConverter.Serializables.MenyooXml;
import java.awt.GraphicsEnvironment;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/**
 *
 * @author tiagocardoso
 */
public class MainGUI extends javax.swing.JFrame {

    private int convertType = 0;

    /**
     * Creates new form MainGUI
     */
    public MainGUI() {
        initComponents();
        initCustomComponents();
        jCbOut.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent ev) {
                convertType = jCbOut.getSelectedIndex();
            }
        });

        Serializer serializer = new Persister();
        try {
            File source = new File("./res/Plane Crash 2.xml");

        } catch (Exception ex) {
            Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 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() {

        jCbOut = new javax.swing.JComboBox<>();
        jCbIn1 = new javax.swing.JComboBox<>();
        btnConvert = new javax.swing.JButton();
        btnClear = new javax.swing.JButton();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767));
        Footer = new javax.swing.JPanel();
        lblCreated = new javax.swing.JLabel();
        lblTotal = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(600, 500));
        setSize(new java.awt.Dimension(600, 500));

        jCbOut.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "GTA:NETWORK - CS", "GTA:NETWORK - XML" }));

        jCbIn1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Guadmaz Map Editor - XML", "Menyoo Object Spooner - XML" }));

        btnConvert.setText("Convert!");
        btnConvert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConvertActionPerformed(evt);
            }
        });

        btnClear.setText("Clear");
        btnClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearActionPerformed(evt);
            }
        });

        lblCreated.setText("GTA:Network - Map Converter by StreetGT");

        lblTotal.setText("Total Converted: 0");

        javax.swing.GroupLayout FooterLayout = new javax.swing.GroupLayout(Footer);
        Footer.setLayout(FooterLayout);
        FooterLayout.setHorizontalGroup(
            FooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(FooterLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTotal)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(lblCreated)
                .addContainerGap())
        );
        FooterLayout.setVerticalGroup(
            FooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, FooterLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(FooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblTotal)
                    .addComponent(lblCreated))
                .addContainerGap())
        );

        jTextArea.setColumns(20);
        jTextArea.setRows(5);
        jScrollPane2.setViewportView(jTextArea);

        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.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jCbIn1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jCbOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnClear, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnConvert, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 593, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2))
                    .addComponent(Footer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCbOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCbIn1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnConvert)
                    .addComponent(btnClear))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(96, 96, 96)
                        .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 232, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Footer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

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

    private void btnConvertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConvertActionPerformed

        Serializer serializer = new Persister();
        try {
            if (jCbIn1.getSelectedIndex() == 0) {
                GuadmazXml map = serializer.read(GuadmazXml.class, jTextArea.getText(), false);
                // Clear TextArea
                jTextArea.setText("");
                GuadmazXml.Objects objects = map.getObjects();
                List<GuadmazXml.MapObject> mapObject = objects.getMapObject();
                lblTotal.setText("Total Converted: " + mapObject.size());
                for (GuadmazXml.MapObject obj : mapObject) {
                    String hash = obj.getHash();
                    String type = obj.getType();
                    String[] position = obj.getPositions();
                    String[] rotation = obj.getRotations();
                    switch (type) {
                        case "Prop": {
                            jTextArea.append(SyntaxConverter.createObject(convertType, hash, position, rotation) + "\n");
                            break;
                        }
                        case "Pickup": {
                            jTextArea.append(SyntaxConverter.createPickup(convertType, hash, position, rotation, obj.getAmount(), obj.getRespawnTimer()) + "\n");
                            break;
                        }
                        case "Ped": {
                            jTextArea.append(SyntaxConverter.createPed(convertType, hash, position, rotation) + "\n");
                            break;
                        }
                        case "Vehicle": {
                            jTextArea.append(SyntaxConverter.createVehicle(convertType, hash, position, rotation, obj.getPrimaryColor(), obj.getSecondaryColor()) + "\n");
                            break;
                        }
                    }
                }
            } else {
                MenyooXml map = serializer.read(MenyooXml.class, jTextArea.getText(), false);
                // Clear TextArea
                jTextArea.setText("");
                List<MenyooXml.Placement> placement = map.getPlacement();
                lblTotal.setText("Total Converted: " + placement.size());
                for (MenyooXml.Placement obj : placement) {
                    String hash = String.valueOf(hex2Decimal(obj.getModelHash()));
                    String[] position = obj.getPositions();
                    String[] rotation = obj.getRotations();
                    int type = obj.getType();
                    switch (type) {
                        case 1: {
                            jTextArea.append(SyntaxConverter.createPed(convertType, hash, position, rotation) + "\n");
                            break;
                        }
                        case 2: {
                            jTextArea.append(SyntaxConverter.createVehicle(convertType, hash, position, rotation, obj.getVehicleProperties().getColours().getPrimary(), obj.getVehicleProperties().getColours().getSecondary()) + "\n");
                            break;
                        }
                        case 3: {
                            jTextArea.append(SyntaxConverter.createObject(convertType, hash, position, rotation) + "\n");
                            break;
                        }
                        case 4: {
                            jTextArea.append(SyntaxConverter.createPickup(convertType, hash, position, rotation, -1, -1) + "\n");
                            break;
                        }
                    }
                }
            }

            JOptionPane.showMessageDialog(this, "Map was converted with success! :)", "Success!", JOptionPane.INFORMATION_MESSAGE);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Ooops! Something went wrong!", JOptionPane.OK_OPTION);
            Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnConvertActionPerformed

    private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed
        jTextArea.setText("");
        lblTotal.setText("Total Converted: 0");
    }//GEN-LAST:event_btnClearActionPerformed

    /**
     * @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(MainGUI.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainGUI.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainGUI.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainGUI.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel Footer;
    private javax.swing.JButton btnClear;
    private javax.swing.JButton btnConvert;
    private javax.swing.Box.Filler filler1;
    private javax.swing.JComboBox<String> jCbIn1;
    private javax.swing.JComboBox<String> jCbOut;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea;
    private javax.swing.JLabel lblCreated;
    private javax.swing.JLabel lblTotal;
    // End of variables declaration//GEN-END:variables

    private void initCustomComponents() {
        this.setTitle("GTANetwork - Map Converter");

        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        this.setMaximizedBounds(env.getMaximumWindowBounds());
        this.setExtendedState(this.getExtendedState() | MainGUI.MAXIMIZED_BOTH);
    }

    public static int hex2Decimal(String s) {
        String digits = "0123456789ABCDEF";
        s = s.toUpperCase();
        int val = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int d = digits.indexOf(c);
            val = 16 * val + d;
        }
        return val;
    }
}
