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

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import tools.*;
import tools.xml.XMLIO;
import static tools.xml.XMLTools.isElement;

/**
 *
 * @author ivanov.i
 */
public class AssemblyJFrame extends javax.swing.JFrame {

	/**
	 * Creates new form AssemblyJFrame
	 */
	public AssemblyJFrame() {
		initComponents();
	}

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

        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Добавить файлик");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id", "lng 1", "lng 2", "lng 3"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton2.setText("Экспортировать");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextField1.setText("1");

        jLabel1.setText("Открываемый столбец");

        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()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(111, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jButton2))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE))
        );

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

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

		
	DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
	int colT = Integer.parseInt(jTextField1.getText());
	
	JFileChooser chooser = new JFileChooser();
	chooser.addChoosableFileFilter(new FileNameExtensionFilter("Android XML", "xml"));
	chooser.addChoosableFileFilter(new FileNameExtensionFilter("Poedit PO", "po"));
    int returnVal = chooser.showOpenDialog(this);
    if(returnVal == JFileChooser.APPROVE_OPTION) 
	{
		if(Tools.afterLast(chooser.getSelectedFile().getName(), ".").toLowerCase().equals("xml"))
		{
			try {

				Document doc = XMLIO.load(chooser.getSelectedFile().getAbsolutePath());

				NodeList nl = doc.getDocumentElement().getChildNodes();
				for (int i = 0; i <nl.getLength(); i++)
				{
					if (isElement(nl.item(i), "string"))
					{
						String msgid=nl.item(i).getAttributes().getNamedItem("name").getNodeValue();
						String msgstr=nl.item(i).getLastChild().getTextContent();
						//nl.item(i).getLastChild().getTextContent().trim()

						int pos = -1;
						for(int ii=0; ii<model.getRowCount(); ii++)
						{
							if(model.getValueAt(ii, 0).equals(msgid))
							{
								pos=i;
								break;
							}
						}
						if(pos!=-1)
						{
							model.setValueAt(msgstr, pos, colT);
						}else
						{
							if(colT==1)
							{
								Object[] row = { msgid, msgstr, "", "" };
								model.addRow(row);
							}else
							if(colT==2)
							{
								Object[] row = { msgid, "", msgstr, "" };
								model.addRow(row);
							}else
							if(colT==3)
							{	Object[] row = { msgid, "", "", msgstr };
								model.addRow(row);
							}
						}
						//System.out.println(nl.item(i).getAttributes().getNamedItem("name").toString());
					}
				}

			} catch (ParserConfigurationException ex) {
				Logger.getLogger(AssemblyJFrame.class.getName()).log(Level.SEVERE, null, ex);
			} catch (IOException ex) {
				Logger.getLogger(AssemblyJFrame.class.getName()).log(Level.SEVERE, null, ex);
			} catch (SAXException ex) {
				Logger.getLogger(AssemblyJFrame.class.getName()).log(Level.SEVERE, null, ex);
			}

		}else
		{
			try
			{
				BufferedReader reader = new BufferedReader(new FileReader(chooser.getSelectedFile().getAbsolutePath()));
				String line;
				String msgid="",msgstr="";
				int cnt=0;
				while (true)
				{
					line = reader.readLine();
					if(line.indexOf("msgid")==0)
					{
						msgid = Tools.beforeLast(Tools.afterFirst(line, "\""),"\"");
						cnt++;
					}
					if(line.indexOf("msgstr")==0)
					{
						msgstr = Tools.beforeLast(Tools.afterFirst(line, "\""),"\"");
						cnt++;
					}
					if(cnt==2)
					{				
						//Ищем идентификатор если он есть то обновляем ячейку если его нет то добавляем строку
						int pos = -1;
						for(int i=0; i<model.getRowCount(); i++)
						{
							if(model.getValueAt(i, 0).equals(msgid))
							{
								pos=i;
								break;
							}
						}
						if(pos!=-1)
						{
							model.setValueAt(msgstr, pos, colT);
						}else
						{
							if(colT==1)
							{
								Object[] row = { msgid, msgstr, "", "" };
								model.addRow(row);
							}else
							if(colT==2)
							{
								Object[] row = { msgid, "", msgstr, "" };
								model.addRow(row);
							}else
							if(colT==3)
							{	Object[] row = { msgid, "", "", msgstr };
								model.addRow(row);
							}
						}
						cnt=0;
					}
				}
			} catch (IOException ex)
			{
				Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
    }

/*
		BufferedReader reader = new BufferedReader(new StringReader(textArea2.getText()));
		String line1;
		String line2;
		try 
		{
			while (true)
			{
				line1 = reader.readLine();
				line2 = reader.readLine();
				if(line1==null || line2 == null) break;
				//Парсим файлы и выписываем идентификаторы для перевода
				parse(line1, line2); //Перезаписывает файл
			}
		} catch (IOException ex)
		{
			Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
		}
*/
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        
		//TODO Записываем в строку в виде HTML строки затем сохраняем в файл
		
    }//GEN-LAST:event_jButton2ActionPerformed

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
