/* $Id: ExportDialog.java 505 2012-05-29 06:41:24Z 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 usersnote;
	private JCheckBox secondidat;
	private JCheckBox thirdidat;
    private JCheckBox caseSensitiveBox;
    private ButtonGroup group2;

    private JCheckBox html;

    protected String currentFileNameBody;
	public ExportDialog(String fileNameBody){
		super(new JFrame(),"Export Dialog");
		this.currentFileNameBody = fileNameBody;
		
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout());
		this.add(mainPanel, BorderLayout.CENTER);
		
		JPanel optionPanel = new JPanel(new BorderLayout());
		mainPanel.add(optionPanel, BorderLayout.CENTER);
		
		
		/*
		 * Scope to export is set in SetScopePanel
		 */
		this.scopePanel = new SetScopePanel(false);

		optionPanel.add(scopePanel,BorderLayout.WEST);
		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.usersnote = new JRadioButton("UsersNote");
		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(usersnote);
		group2.add(allType);
		
		firstidat.addActionListener(new DocumentTypeCheckBoxSelectAction());
		secondidat.addActionListener(new DocumentTypeCheckBoxSelectAction());
		thirdidat.addActionListener(new DocumentTypeCheckBoxSelectAction());
		usersnote.addActionListener(new DocumentTypeSelectAction());
		allType.addActionListener(new DocumentTypeSelectAction());

		
		documentTypePanel.add(firstidat);
		documentTypePanel.add(secondidat);
		documentTypePanel.add(thirdidat);
		documentTypePanel.add(usersnote);
		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.pack();
		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(usersnote.isSelected()){
				documentTypeList.add(new Integer(ExportConstants.USERSNOTE));
			}
			export(documentTypeList);
		}
	}
	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(usersnote.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){
		List<Spread> spreads = this.scopePanel.getSpreadsToSearch();
		String htmlbase = null;
		if(html.isSelected()){
			htmlbase = ExportHtmlCreater.getHTMLStr();
			htmlbase = insertCodeSetMetaElement(htmlbase);
		}
		
		// ファイルの保存
		String currentDirectory = Preference.getInstance().getSmart_exportFolderPathString();
		if(currentDirectory == null){
			currentDirectory = "./";
		}
		File directory = new File(currentDirectory);
		JFileChooser chooser = new JFileChooser(directory);
		if (this.currentFileNameBody != null) {
			if(html.isSelected()){
				chooser.setSelectedFile(new File(this.currentFileNameBody + ".html"));
			}else{
				chooser.setSelectedFile(new File(this.currentFileNameBody + ".txt"));
			}
		}
		//
		
		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) {
			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 usersnotemode = false;
			writer = new OutputStreamWriter(new FileOutputStream(path), "UTF-8");
			if(documentTypeList.size() == 1){
				Integer documentType = documentTypeList.get(0);
				if(documentType.intValue() ==  ExportConstants.USERSNOTE){
					usersnotemode = true;
				}
			}
			if(usersnotemode){
				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();
	}
	
//	Shayashi 2012.05.24. This should be replaced with a method acting
//	on HTMLDocument instead of its string representation.
	private String insertCodeSetMetaElement(String htmlbase) {
		return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + htmlbase;
	}

	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;
	}

}
