/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package potoxml;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.table.DefaultTableModel;
import org.ini4j.Ini;

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

	/**
	 * Creates new form NewJFrame
	 */
	public NewJFrame()
	{
            initComponents();
     
            setTitle("GettextDB");
            
            try {
                File file = new File("settings.ini");
                if(file.exists()){           
                    Ini ini = new Ini(file);
                    jTFDBURL.setText(ini.get("main", "db_url"));
                    jTFDBUser.setText(ini.get("main", "db_user"));
                    jTFDBPassword.setText(ini.get("main", "db_password"));

                    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
                    for(int i=0;i<100;i++){
                        if(ini.get("path"+i)!=null){
                            String path = ini.get("path"+i, "path");
                            String check = ini.get("path"+i, "check");
                            String extensions = ini.get("path"+i, "extensions");
                            String pattern = ini.get("path"+i, "pattern");
                            String type = ini.get("path"+i, "type");
                            model.addRow(new Object[]{path, extensions, pattern, check, type });
                            System.out.print(path);
                        }
                    }
                    //ini.store();
                }
            } catch (IOException ex) {
                Logger.getLogger(NewJFrame.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() {

        jPanel4 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jTFDBURL = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTFDBUser = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTFDBPassword = new javax.swing.JTextField();
        jButton5 = new javax.swing.JButton();
        jBSaveSettings = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        textArea1 = new java.awt.TextArea();
        jButton3 = new javax.swing.JButton();
        jCheckBox1 = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

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

            },
            new String [] {
                "Файл/Путь", "Расширения файлов", "Шаблон поиска", "Шаблон проверки", "ID типа слов"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };

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

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 915, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Настройки путей сканирования", jPanel2);

        jLabel4.setText("Строка соединения");

        jTFDBURL.setText("jdbc:postgresql://10.1.7.74:5432/pilot");

        jLabel5.setText("Пользователь");

        jTFDBUser.setText("translate");

        jLabel6.setText("Пароль");

        jTFDBPassword.setText("translate");

        jButton5.setText("Проверить соединение");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTFDBPassword)
                            .addComponent(jTFDBUser)
                            .addComponent(jTFDBURL, javax.swing.GroupLayout.DEFAULT_SIZE, 790, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton5)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFDBURL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFDBUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFDBPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton5)
                .addContainerGap(36, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Настройки соединения с базой", jPanel3);

        jBSaveSettings.setText("Сохранить настройки");
        jBSaveSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSaveSettingsActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTabbedPane1)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jBSaveSettings)))
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBSaveSettings)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jButton1.setText("Сканировать");
        jButton1.setName(""); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("Экспорт PO или XML файла");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jCheckBox1.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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textArea1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 298, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jCheckBox1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton3)
                    .addComponent(jCheckBox1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

	private void parse(String rootDir,String extensions,String pattern,String check,String type)
	{
		// Просматриваем каталоги
		FileFinder finder = new FileFinder();
		try
		{
			// Буферный файл для записи идентификаторов
			//FileWriter fileWriter = new FileWriter(file);
			//BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
			//bufferedWriter.write("<?\n");

			List searchRes = null;
			//searchRes = finder.findAll(rootDir,"(.*\\.as$)||(.*\\.mxml$)||(.*\\.xml$)");
                        searchRes = finder.findAll(rootDir,"(.*\\.php$)||(.*\\.html$)||(.*\\.xml$)||(.*\\.js$)");
			
			//выводим результаты
			for (int i = 0; i < searchRes.size(); i++)
			{
				File curObject = (File) searchRes.get(i);
				if (curObject.isDirectory())
				{					
					System.out.println(curObject.getName() + " (папка)");
					textArea1.append(curObject.getAbsolutePath() + " (папка)\n");
				} else
				{
					System.out.println(curObject.getName() + " (" + curObject.length() + " байт)");
					textArea1.append(curObject.getAbsolutePath() + " (" + curObject.length() + " байт)\n");
					
					
					// Открываем файл и ищем идентификаторы
					FileReader fileReader = new FileReader(curObject.getAbsolutePath());
					BufferedReader bufferedReader = new BufferedReader(fileReader);
					String line;
					//bufferedWriter.write("1\n");
					while((line = bufferedReader.readLine()) != null)
					{
						int from=0;
                                                int to=0;
						while(true) //Если несколько значений в строке
						{
                                                    int s=line.indexOf(pattern, from);
                                                    if(s>=0)
                                                    {
                                                        from=s+pattern.length();
                                                        to=line.indexOf(")", from);
                                                        //int e=-1;
                                                        //if(line.charAt(s+pattern.length()) == '"') { e=line.indexOf("\")", from); }
                                                        //if(line.charAt(s+pattern.length()) == '\'') { e = line.indexOf("')", from); }
                                                        if(to>=0)
                                                        {
                                                            String text = line.substring(from, to);
                                                            if(text.indexOf("\"")>=0){ //Если строка с "
                                                                int pos1 = text.indexOf("\"");
                                                                int pos2 = text.indexOf("\"",pos1+1);
                                                                if(pos2>pos1+1){
                                                                    text = text.substring(pos1+1, pos2);
                                                                }else{
                                                                    text="";
                                                                }
                                                            } else 
                                                            if(text.indexOf("'")>=0){ //Если строка с '
                                                                int pos1 = text.indexOf("'");
                                                                int pos2 = text.indexOf("'",pos1+1);
                                                                if(pos2>pos1+1){
                                                                    text = text.substring(pos1+1, pos2);
                                                                }else{
                                                                    text="";
                                                                }
                                                            }else{
                                                                text="";
                                                            }

                                                            if(text.length()>0){
                                                                if(text.matches("[0-9|a-z|A-Z|_]+")){
                                                                    textArea1.append(text+"\n");
                                                                }else{
                                                                    textArea1.append("NO VALUD = "+text+"\n");
                                                                }
                                                            }
                                                            from+=to-from;
                                                        }
                                                        from+=1;
                                                    }else { break; }
                                                    //line=line.substring(to); //Остатки строки на обработку
						}
					}	
					bufferedReader.close();
				}
			}
			//System.out.println("Найдено " + finder.getFilesNumber() + " файлов и " + finder.getDirectoriesNumber() + " папок.");
			textArea1.append("Найдено " + finder.getFilesNumber() + " файлов и " + finder.getDirectoriesNumber() + " папок.\n");
			
			//bufferedWriter.write("?>\n");
			//bufferedWriter.close();
					
		} catch (Exception err)
		{
			System.out.println(err.getMessage());
		}
	}

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton1ActionPerformed
    {//GEN-HEADEREND:event_jButton1ActionPerformed
	//Подключаюсь к базе данных   
        String url = jTFDBURL.getText(); //"jdbc:postgresql://10.1.7.74:5432/pilot";
        String user = jTFDBUser.getText(); //"translate";
        String password = jTFDBUser.getText(); //"translate";
        Connection conn = null;
        try {
            Class.forName("org.postgresql.Driver");            
            conn = DriverManager.getConnection(url, user, password);
            System.out.println("Connected to the PostgreSQL server successfully.");
        }catch(ClassNotFoundException | SQLException e){
            System.out.println(e.getMessage());
        }

        //Перебираю значения таблицы и пускаю на сканирование каждое поле
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        for(int row=0;row<model.getRowCount();row++){
            parse(
                    model.getValueAt(row,0).toString(),
                    model.getValueAt(row,1).toString(),
                    model.getValueAt(row,2).toString(),
                    model.getValueAt(row,3).toString(),
                    model.getValueAt(row,4).toString()
            );
        }

    }//GEN-LAST:event_jButton1ActionPerformed

	
    private void jBSaveSettingsActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jBSaveSettingsActionPerformed
    {//GEN-HEADEREND:event_jBSaveSettingsActionPerformed
        try
        {
            Ini ini = new Ini(new File("settings.ini"));
            ini.put("main", "db_url", jTFDBURL.getText());
            ini.put("main", "db_user", jTFDBUser.getText());
            ini.put("main", "db_password", jTFDBPassword.getText());
            ini.store();
        } catch (IOException ex)
        {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jBSaveSettingsActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        
		new AssemblyJFrame().setVisible(true);
		
    }//GEN-LAST:event_jButton3ActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
       

        

    }//GEN-LAST:event_formWindowActivated

	/**
	 * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex)
		{
			java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex)
		{
			java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex)
		{
			java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
			}
		});
	}
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBSaveSettings;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton5;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTFDBPassword;
    private javax.swing.JTextField jTFDBURL;
    private javax.swing.JTextField jTFDBUser;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private java.awt.TextArea textArea1;
    // End of variables declaration//GEN-END:variables
}
