/*
 * 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;



import java.io.IOException;

import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Vector;


import wsdde.general.Config;
import wsdde.general.Config.*;

import ipipan.poliqarp.connection.PoliqarpConnection;
import ipipan.poliqarp.logic.Corpus;
import ipipan.poliqarp.logic.CorpusNotOpenedException;
import ipipan.poliqarp.logic.MatchList;
import ipipan.poliqarp.logic.Query;
import ipipan.poliqarp.logic.QueryException;
import ipipan.poliqarp.logic.Corpus.State;


/**
 * @author Rafał Młodzki
 * @author Marcin Młodzki
 *
 */
public class Pseudowords {
	
	 private PoliqarpConnection connection;
	 private Corpus corpus;
	 
	 private String serverName;
	 private int portNumber;
	 private String corpusFileName;
		 
	 private String [] parametersWords;
	 private int [] parametersLength;
	 private String pseudoMatch;
	 
	 private Vector<PoliqarpContext> contexts;
	 
	 private void initConfig() 
	 {
		 serverName = Config.property(Settings.POLIQARP_SERVER);
		 portNumber = Integer.parseInt(Config.property(Settings.POLIQARP_PORT));
		 corpusFileName = Config.property(Settings.POLIQARP_CORPUS);
	 }
	 
	 public Pseudowords(String [] pp, int [] pl){
		parametersWords = pp;
		parametersLength = pl;
		autoSetPseudoMatch();
		initConfig();
	 }
	 
	 private void autoSetPseudoMatch(){
		 pseudoMatch = "";
		 for(int i = 0; i < parametersWords.length; i++){
			 pseudoMatch = pseudoMatch  + parametersWords[i];
		 }
	 }
	 
	 public void setPseudoMatch(String pM){
		 pseudoMatch = pM;
	 }
	

	private void retrieveAllContexts() throws UnknownHostException, IOException, CorpusNotOpenedException, InterruptedException, QueryException {
		connection = new PoliqarpConnection(serverName, portNumber);
		try {
			corpus = new Corpus(connection, corpusFileName, null);
			while(corpus.getState()==State.OPENING){
				Thread.sleep(10);
			}
			switch(corpus.getState()){
			case OPENED:
				contexts = new Vector<PoliqarpContext>();
				for(int i = 0; i < parametersWords.length; i++){
					retrieveWordContexts(i);
				}
				break;
			case NOT_OPENED:
//				System.out.println(corpus.getLastError());
				throw(new IOException (corpus.getLastError()));
			}
		}
		finally{
			connection.close();
		}				
	}
	
	/**
	 * 
	 * @param paramNum
	 * @throws QueryException
	 * @throws InterruptedException
	 * @throws IOException if an I/O exception occurred
	 */
	private void retrieveWordContexts(int paramNum) throws QueryException, InterruptedException, IOException{
		int paramLen = parametersLength[paramNum];
		Query q = new Query(connection, parametersWords[paramNum]);
		q.launch(null);
		while (q.isRunning()) {
			//System.out.print(".");
            //System.out.print(q.getProgress());
            Thread.sleep(500);
        }
		//System.out.println(".OK");
        MatchList ml = q.getMatchList();
        //System.out.println(ml.count());//.getCell(1)+" ***");
        Thread.sleep(500);
        int maxCount = (ml.count() > paramLen)?paramLen:ml.count();
        for (int i=0;i< maxCount;i++){
    		PoliqarpContext con = new PoliqarpContext(connection, i);
    		con.setPseudoMatch(pseudoMatch);
    		contexts.add(con);
        }
	}
	
	/**
	 * Generate string containing xml with contexts
	 * 
	 * @return xml with contexts
	 */
	private String getXMLContexts(){
		String xmlContexts = "<wsdcorpus>";
		for(int i=0; i < contexts.size(); i++){
			xmlContexts +=  contexts.get(i).toXML()+ "\n";
		}
		xmlContexts += "</wsdcorpus>";
		return xmlContexts;
	}	  
	  
	
	public static String getPseudowordsCorpus(String [] pp, int [] pl ) {
		Pseudowords pi = new Pseudowords(pp, pl);
		try {
			pi.retrieveAllContexts();
			return pi.getXMLContexts();
		} catch(Exception e){
			System.err.println("Error while connecting or retreving data from poliqarp server");
			e.printStackTrace();
		}
		return null;		
	}
	 
	
	public static void main(String[] args) throws UnknownHostException, IOException {
		//System.out.print("END");
		String [] words = { "pies","kot","suka"};
		int [] maxContext = {1,2,3};
	
		String contextXML = getPseudowordsCorpus(words, maxContext);
		System.out.println(contextXML);
	
		//InetAddress machine = InetAddress.getByName ("192.168.2.150");
		//new Socket(machine, 3306);
		

	}


}
