/* $Id: ExportDialog.java 344 2011-09-08 13:43:20Z shayashi $ */
package smart_gs.menu.export;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;

import smart_gs.PreferenceManager;
import smart_gs.logical.Preference;
import smart_gs.logical.UsersNote;
import smart_gs.logical.UsersNoteTree;
import smart_gs.logical.Spread;
import smart_gs.spread_selection.SetScopePanel;
import smart_gs.swingui.WorkspaceWindow;
import smart_gs.swingui.toolbar.action.HTMLFileFilter;
import smart_gs.swingui.toolbar.action.TextFileFilter;
import smart_gs.util.CanonicalPathString;
import smart_gs.util.StringUtils;


@SuppressWarnings("serial")

public class ExportDialog extends JDialog  {
	//検索範囲の指定
	private SetScopePanel scopePanel;
	
	private JRadioButton allType;
	private JRadioButton docType;
	private JCheckBox firstidat;
	//20080901. Textの検索のためのラジオボタンを設置
	private JRadioButton text;
	private JCheckBox secondidat;
	private JCheckBox thirdidat;
    private JCheckBox caseSensitiveBox;
    private ButtonGroup group2;

    private JCheckBox html;

    protected File currentFile;
	public ExportDialog(File currentFile){
		super(new JFrame(),"Export Dialog");
		this.currentFile = currentFile;
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout());
		this.add(mainPanel, BorderLayout.CENTER);
		
		JPanel optionPanel = new JPanel(new GridLayout(1,2));
		mainPanel.add(optionPanel, BorderLayout.CENTER);
		
		
		/*
		 * 検索範囲の指定をSetScopePanelに移した
		 */
		this.scopePanel = new SetScopePanel(false);

		optionPanel.add(scopePanel);
		html = new JCheckBox("Export by HTML");
		mainPanel.add(html, BorderLayout.SOUTH);
		
		JPanel documentTypePanel = new JPanel(new GridLayout(4,1));
		documentTypePanel.setBorder(new TitledBorder("document type"));
		this.docType = new JRadioButton("document");
		this.text = new JRadioButton("Text");
		this.firstidat = new JCheckBox(Preference.getInstance().getFirstIDATName());
		this.firstidat.setSelected(true);
		this.secondidat = new JCheckBox(Preference.getInstance().getSecondIDATName());
		this.thirdidat = new JCheckBox(Preference.getInstance().getThirdIDATName());
		this.allType = new JRadioButton("All Document Types");
		group2 = new ButtonGroup();
		


	
		
		group2.add(docType);
		group2.add(text);
		group2.add(allType);
		
		firstidat.addActionListener(new DocumentTypeCheckBoxSelectAction());
		secondidat.addActionListener(new DocumentTypeCheckBoxSelectAction());
		thirdidat.addActionListener(new DocumentTypeCheckBoxSelectAction());
		text.addActionListener(new DocumentTypeSelectAction());
		allType.addActionListener(new DocumentTypeSelectAction());

		
		documentTypePanel.add(firstidat);
		documentTypePanel.add(secondidat);
		documentTypePanel.add(thirdidat);
		documentTypePanel.add(text);
		documentTypePanel.add(allType);
		optionPanel.add(documentTypePanel);
		
		JPanel buttonPanel = new JPanel();
		JButton ok = new JButton("Save");
		ok.addActionListener(new OKAction());
		buttonPanel.add(ok);
		
		JButton cancel = new JButton("Cancel");
		cancel.addActionListener(new CancelAction());
		buttonPanel.add(cancel);
		
		this.getContentPane().add(mainPanel,BorderLayout.CENTER);
		this.getContentPane().add(buttonPanel,BorderLayout.SOUTH);
		this.setLocationRelativeTo(null);
		this.pack();
	}
	private class OKAction implements ActionListener{
		ArrayList<Integer> documentTypeList = new ArrayList<Integer>();
		public void actionPerformed(ActionEvent e){
//			queryText = queryTextPane.getText();
			if(firstidat.isSelected()) {
				documentTypeList.add(new Integer(ExportConstants.FIRSTIDAT));
			}
			if(thirdidat.isSelected()){
				documentTypeList.add(new Integer(ExportConstants.THIRDIDAT));
			}
			if(secondidat.isSelected()){
				documentTypeList.add(new Integer(ExportConstants.SECONDIDAT));
			}
			if(allType.isSelected()){
				documentTypeList.add(new Integer(ExportConstants.ALLDOCUMENT));
			}
			if(text.isSelected()){
				documentTypeList.add(new Integer(ExportConstants.TEXT));
			}
			export(documentTypeList,caseSensitiveBox.isSelected());
		}
	}
	private class DocumentTypeCheckBoxSelectAction implements ActionListener{
		public void actionPerformed(ActionEvent e){
			scopePanel.setEnabled(true);
			docType.setSelected(true);
		}
	}

	private class DocumentTypeSelectAction implements ActionListener{
		public void actionPerformed(ActionEvent e){
			if(text.isSelected()){
				firstidat.setSelected(false);
				thirdidat.setSelected(false);
				secondidat.setSelected(false);
				scopePanel.setEnabled(false);
			}else {
				scopePanel.setEnabled(true);
			}
			if(allType.isSelected()){
				firstidat.setSelected(false);
				thirdidat.setSelected(false);
				secondidat.setSelected(false);
			}
		}
	}

	private class CancelAction implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			System.out.println("canceled");
			dispose();
		}
	}

	private void export(ArrayList<Integer> documentTypeList,boolean isCaseSensitive){
//		List<Spread> spreads = this.getSpreadsToSearch();
		List<Spread> spreads = this.scopePanel.getSpreadsToSearch();
		String htmlbase = null;
		if(html.isSelected()){
			htmlbase = ExportHtmlCreater.getHTMLStr();
		}
		
		// ファイルの保存
		String currentDirectory = Preference.getInstance().getSmart_exportFolderPathString();
		if(currentDirectory == null){
			currentDirectory = "C:/";
		}
		File directory = new File(currentDirectory);
		JFileChooser chooser = new JFileChooser(directory);
		if (this.currentFile != null) {
			chooser.setSelectedFile(this.currentFile);
		}
		//
		
		FileFilter fileFilter;
		if(html.isSelected()){
			fileFilter = new HTMLFileFilter();
		}else{
			fileFilter = new TextFileFilter();
		}
		chooser.setFileFilter(fileFilter);
		int input = chooser.showSaveDialog(WorkspaceWindow.getInstance());
		if (input == JFileChooser.CANCEL_OPTION) {
			dispose();
			return;
		}
		File file = chooser.getSelectedFile();
		String path = CanonicalPathString.get(file);
		if(!path.toLowerCase().endsWith("." + fileFilter.getDescription() )){
			if(path.endsWith(".")){
				path += fileFilter.getDescription();
			}else{
				path += "." + fileFilter.getDescription();
			}
		}
		OutputStreamWriter writer = null;
		StringBuffer buf = new StringBuffer();
		String br = null;
		if(html.isSelected()){
			br = "<br>\n";
		}else{
			br = "\n";
		}
		try{
			boolean textmode = false;
			writer = new OutputStreamWriter(new FileOutputStream(path), "UTF-8");
			if(documentTypeList.size() == 1){
				Integer documentType = documentTypeList.get(0);
				if(documentType.intValue() ==  ExportConstants.TEXT){
					textmode = true;
				}
			}
			if(textmode){
				boolean isBr = false;
				ArrayList<UsersNote> arrList1 = (ArrayList<UsersNote>) UsersNoteTree.getInstance().getUsersNotes();
				Iterator<UsersNote> itr = arrList1.iterator();
				while (itr.hasNext()) {
					UsersNote usersNote = itr.next();
					String xmlstr = usersNote.getSource();
					if(html.isSelected()){
						xmlstr = getHtml(xmlstr);
					}else{
						xmlstr = getText(xmlstr);
					}
			        if(!xmlstr.trim().equals("")){
			        	buf.append(xmlstr);
			        	buf.append(br);
				        isBr = true;
			        }
					if(isBr){
						buf.append(br);
					}
				}
			}else{
				for(int i=0;i<spreads.size();i++){
					Spread spread = spreads.get(i);
					boolean isBr = false;
					for(int j=0;j<documentTypeList.size();j++){
						int documentType = documentTypeList.get(j).intValue();
						// Transcription
						{
							if(documentType == ExportConstants.FIRSTIDAT || documentType == ExportConstants.ALLDOCUMENT){
								String xmlstr = spread.getFirstIDAT().getSource();
								if(html.isSelected()){
									xmlstr = getHtml(xmlstr);
								}else{
									xmlstr = getText(xmlstr);
								}
						        if(!xmlstr.trim().equals("")){
						        	buf.append(xmlstr);
						        	buf.append(br);
							        isBr = true;
						        }
							}
						}
						// SecondIDAT
						{
							if(documentType == ExportConstants.SECONDIDAT || documentType == ExportConstants.ALLDOCUMENT){
								String xmlstr = spread.getSecondIDAT().getSource();
								if(html.isSelected()){
									xmlstr = getHtml(xmlstr);
								}else{
									xmlstr = getText(xmlstr);
								}
						        if(!xmlstr.trim().equals("")){
						        	buf.append(xmlstr);
						        	buf.append(br);
							        isBr = true;
						        }
							}
						}
						// ThirdIDAT
						{
							if(documentType == ExportConstants.THIRDIDAT || documentType == ExportConstants.ALLDOCUMENT){
								String xmlstr = spread.getThirdIDAT().getSource();
								if(html.isSelected()){
									xmlstr = getHtml(xmlstr);
								}else{
									xmlstr = getText(xmlstr);
								}
						        if(!xmlstr.trim().equals("")){
						        	buf.append(xmlstr);
						        	buf.append(br);
							        isBr = true;
						        }
							}
						}
						if(isBr){
							buf.append(br);
						}
					}
				}
				{
					//Text
					boolean outputText = false;
					for(int i = 0; i < documentTypeList.size(); i++ ){
						Integer documentType = documentTypeList.get(i);
						if(documentType.intValue() ==  ExportConstants.ALLDOCUMENT){
							outputText = true;
						}
					}

					if(outputText){
						boolean isBr = false;
						ArrayList<UsersNote> arrList1 = (ArrayList<UsersNote>) UsersNoteTree.getInstance().getUsersNotes();
						Iterator<UsersNote> itr = arrList1.iterator();
						while (itr.hasNext()) {
							UsersNote usersNote = itr.next();
							String xmlstr = usersNote.getSource();
							if(html.isSelected()){
								xmlstr = getHtml(xmlstr);
							}else{
								xmlstr = getText(xmlstr);
							}
					        if(!xmlstr.trim().equals("")){
					        	buf.append(xmlstr);
					        	buf.append(br);
						        isBr = true;
					        }
							if(isBr){
								buf.append(br);
							}
						}
					}
				}
			}
			if(html.isSelected()){
				String writeStr;
				if(htmlbase != null){
					writeStr = htmlbase;
					writeStr = StringUtils.replaceString(writeStr, "$BODY$", buf.toString());
				}else{
					writeStr = buf.toString();
				}
				writer.write(writeStr);
			}else{
				writer.write(buf.toString());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(writer != null){
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		dispose();
	}
	
	public void actionPerformed(ActionEvent e) {
		
	}
	protected String getText(String str){
		String xmlstr = StringUtils.replaceString(str, "<br>", "\n");
		Pattern pattern = Pattern.compile("<.+?>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(xmlstr);
        xmlstr = matcher.replaceAll("");
        xmlstr = xmlstr.trim();
        return xmlstr;
	}
	protected String getHtml(String str){
		if(str.startsWith("<xml><html>")){
			if(str.endsWith("</html></xml>")){
				return str.substring(str.indexOf("<xml><html>") + "<xml><html>".length(),str.lastIndexOf("</html></xml>"));
			}
		}
		return null;
	}

}
