/*
 * Copyright (C) 2009 by Instytut Podstaw Informatyki Polskiej
 * Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 * Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 *
 * This file is part of WSDDE.
 *
 * WSDDE is free software: it may be distributed and/or modified under
 * the terms of the GNU General Public License version 3 as published
 * by the Free Software Foundation and appearing in the file doc/gpl.txt
 * included in the packaging of this file.
 *
 * A commercial license is available from IPI PAN (contact
 * Michal.Ciesiolka@ipipan.waw.pl or ipi@ipipan.waw.pl for more
 * information).  Licensees holding a valid commercial license from IPI
 * PAN may use this file in accordance with that license.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

package wsdde.corpus.knowledge;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import wsdde.corpus.WSDCorpus;
import wsdde.general.Config;


public class TAKIPIManager extends KnowledgeSource {

	/*static public final String takipiDir = "c:\\tmp\\takipi";
	static public final String takipiPath = takipiDir+"\\takipi.exe";
	static public final String takipiEncoding= "-UTF";*/
	
	
	
	//static public final String takipiDir = "c:\\tmp\\takipi";
	//static public final String takipiPath = "takipi.bin";
	static public final String takipiEncoding= "-UTF";
	
	//static public String directory = "takipitmp";
	//Dostaje zwykle WIKIKWIKI
	//PRZYGOTOWUJE KATALOG, META.TXT z lista plikow, pliki z kontekstami
	//odpala takipi
	//wczytuje xmla i robi KWICS (nowe, oznakowane)
	
	@Override
	public WSDCorpus enrich(String filename) {
		takipi(filename);
		return read(filename+".takipized");
	}
	
	public static WSDCorpus read(String filename) {
		TakipiXMLParser parser = new TakipiXMLParser();
		return parser.parse(filename);
	}
	
	
	public static void takipi(String filename) {
		String meta = "";

		try {
			//meta = new File(directory+"/meta.txt").getCanonicalPath();
			meta = new File(filename).getCanonicalPath();
		} catch (IOException e2) {
			
			e2.printStackTrace();
		}
		
		//ProcessBuilder pb = new ProcessBuilder( "takipi", "-i", meta,"-o",meta+".takipized","-UTF","-TXT");
		//ProcessBuilder pb = new ProcessBuilder( "c:\\tmp\\takipi\\takipi.exe", "-i", meta,"-o",meta+".takipized","-UTF","-TXT");
		ProcessBuilder pb = new ProcessBuilder( Config.Settings.TAKIPI_BIN.value(), "-i", meta,"-o",meta+".takipized","-UTF","-TXT");
		
		Map<String, String> env = pb.environment();
		// insert set FRUIT=strawberry into environment just for our children
		//env.put( "FRUIT", "strawberry" );

		// remove set LIVERCOURSE=YES from environment just for our children
		//env.remove( "LIVERCOURSE" );

		// modify set WINE=pinot to WINE=pinot blanc
		//env.put( "WINE", env.get("WINE") + " blanc" );

		// set up the working directory.
		// Note the method is called "directory" not "setDirectory"
	//	if (Wlasciwosci.Settings.TAKIPI_BIN.value().endsWith("takipi.exe")) {
		//	pb.directory( new File("c:\\Documents and Settings\\Administrator\\My Documents\\PAN\\zasoby\\takipi"));// "c:\\tmp\\takipi") );
		if (Config.Settings.TAKIPI_BIN.value().endsWith(".exe")) {
			try {
				pb.directory( new File(Config.Settings.TAKIPI_BIN.value()).getParentFile().getCanonicalFile());
			} catch (IOException e) {
				e.printStackTrace();
			}// "c:\\tmp\\takipi") );
		}
	//	}

		// merge child's error and normal output streams.
		// Note it is not called setRedirectErrorStream.
		pb.redirectErrorStream( true );
		Process p;
		try {
			p = pb.start();
		
		final InputStream is = p.getInputStream();
        final InputStreamReader isr = new InputStreamReader( is );
        final BufferedReader br = new BufferedReader( isr, 100/* buffsize in chars */ );
        String line;
        try
            {
            try
                {
                // C/C++ can write this with putc
                while ( ( line = br.readLine() ) != null )
                    {
                    System.out.println( line );

                    }
                }
            catch ( EOFException e )
                {
                }
            br.close();
            }
        catch ( IOException e )
            {
            System.err.println( "problem reading spawn output" + e.getMessage() );
            System.exit( 1 );
            }
        // returning from run kills the thread.
        
		// From here on it, it behaves just like exec, since you have the
		// exact same Process object.
		// ...

		// You can reuse the ProcessBuilder objects.
		// They retain their initialisation.
		//Process sister = pb.start();
		
	//	Runtime rt = Runtime.getRuntime();
	//	String [] env = {"-i c:\\tmp\\cynamonowe.txt -it TXT -o c:\\tmp\\cyn.out"};
	//	Process p = rt.exec("c:\\tmp\\takipi\\takipi.exe",env);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	
	
	public static void main(String [] args) {
		
	//	WSDCorpus w = processAndRead("marcin_jezyk.xml");
		//WSDCorpus.save(w, "test.wsdcorp");
		
		WSDCorpus w = new TAKIPIManager().enrich("powod.xml");
		WSDCorpus.saveTXT(w, "takipi.wsdc");
		
		//WSDCorpus w = processAndRead("literacki.xml");
		//WSDCorpus w = processAndRead("zmyslowy.xml");
		//WSDCorpus.save(w, "test.wsdcorp");
		
	}
}


