/* Copyright (c) 2012,
 * Mathias Kuhring, KuhringM@rki.de, Robert Koch-Institut, Germany, 
 * All rights reserved. For details, please note the license.txt.
 */

package de.rki.ng4.ipig.tools;

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.IOException;
import java.util.Arrays;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 * Tool to convert a Mascot CSV to an tab separated txt file with the columns and the format like required by the ipig.
 * 
 * This tool is not fully tested, so it maybe only works with fully exported Mascot CSVs.
 * Its more for development use and it is actually not a part of the ipig yet.
 * 
 * @author Mathias Kuhring
 *
 */
public class MascotCSV2TXT {

	public static void main(String[] args) {
		final String[] temp = {"prot_acc", "prot_desc", "pep_query", "pep_isunique", "pep_exp_z", "pep_score", "pep_seq", "pep_var_mod", "pep_var_mod_pos"};
		final Vector<String> colNames = new Vector<String>(Arrays.asList(temp));

		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch(Exception e) {
			System.out.println("Error setting native LAF: " + e);
		}
		
		File file = null;
		if (args.length == 0){
			JFileChooser fc = new JFileChooser();
			fc.setFileFilter(new FileNameExtensionFilter("mascot csv", "csv"));
			
			int state = fc.showOpenDialog( null );

			if ( state == JFileChooser.APPROVE_OPTION )
			{
				file = fc.getSelectedFile();
			}
			else
				System.exit(0);
		}	
		else
			file = new File(args[0]);
		
		String filename = file.getName().substring(0, file.getName().lastIndexOf("."));
		String path = file.getParent();
		
		try{
		BufferedReader input = new BufferedReader(new FileReader(file));
		BufferedWriter output = new BufferedWriter(new FileWriter(path + "/" + filename + ".txt"));
		
		boolean isMascot = false;
		boolean unique = false;
		
		Pattern p = Pattern.compile("(\"(?:[^\"]|\"\")*\"|[^\",\r\n]*)(,|\r\n?|\n)?");
		Matcher m;
		Vector<String> fields = new Vector<String>();
		
		Vector<Integer> cols = new Vector<Integer>();
		String line;
		while (input.ready()){
			line = input.readLine();
			if (isMascot = line.startsWith("prot_hit_num")){

				m = p.matcher(line);
				while ( m.find() ){
					String field = m.group();
					if (field.endsWith(",") || field.endsWith(";"))
						field = field.substring(0, field.length()-1);
					while (field.startsWith("\"") && field.endsWith("\""))
						field = field.substring(1, field.length()-1);
					while (field.startsWith(" "))
						field = field.substring(1, field.length());
					fields.add(field);
				}
				
				for (int i=0; i<fields.size(); i++){
					if (colNames.contains(fields.get(i))){
						cols.add(i);
					}
					if (fields.get(i).matches("pep_isunique"))
						unique = true;
				}
				isMascot = cols.size() > 0;
				break;
			}
		}
		if (isMascot){
			Vector<String> header = new Vector<String>();
			for (int i=0; i<cols.size()-1; i++){
				header.add(fields.get(cols.get(i)) + "\t");
			}
			header.add(fields.get(cols.lastElement()));
			if (!unique)
				header.add(3, "pep_isunique\t");
			header.lastElement().replace("\\t", "");
			
			for (String s : header)
				output.write(s);
			output.newLine();
			
			while (input.ready()){
				m = p.matcher(input.readLine());
				fields = new Vector<String>();
				while ( m.find() ){
					String field = m.group();
					if (field.endsWith(",") || field.endsWith(";"))
						field = field.substring(0, field.length()-1);
					while (field.startsWith("\"") && field.endsWith("\""))
						field = field.substring(1, field.length()-1);
					while (field.startsWith(" "))
						field = field.substring(1, field.length());
					fields.add(field);
				}
								
				Vector<String> out = new Vector<String>();
				for (int i=0; i<cols.size()-1; i++){
					out.add(fields.get(cols.get(i)) + "\t");
				}
				out.add(fields.get(cols.lastElement()));
				if (!unique)
					out.add(3, "1\t");
				
				for (String s : out)
					output.write(s);
				output.newLine();
			}
			
			input.close();
			output.close();
			
			System.out.println("done");
		}
		else
			System.out.println("error:\tcouldn't find nessecary data in " + file.getName() +
					"\n\t" + "header should start with \"prot_hit_num\" and contain following fields:" +
					"\n\t" + colNames.toString() +
					"\n\t" + "(if pep_isunique is missing it is assumed that peptides are unique)");
	
		}
		catch (FileNotFoundException e) {
			System.out.println(e.getLocalizedMessage());
		} 
		catch (IOException e) {
			System.out.println(e.getLocalizedMessage());
		}
	}
}
