/*
 * Copyright 2010 PC-NG Inc. All rights reserved.
 * PC-NG PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nexiwave.search.client.sample;

import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

import com.nexiwave.search.client.SearchService2Stub;
import com.nexiwave.search.client.SearchService2Stub.AddResponse;
import com.nexiwave.search.client.SearchService2Stub.AttachHumanTranscriptionResponse;

public class RestSampleClient {
	public void testAttachHumanTranscription()throws java.lang.Exception{
		
		// upload a recording from http://test.nexiwave.com/static/audio/test.wav
		String url=getBaseURL("add")+"&media=http://test.nexiwave.com/static/audio/test.wav";
		String result=get(url);
		
		// parse the result:
		AddResponse resp=SearchService2Stub.AddResponse.Factory.parse(toXMLStreamReader(result));
		long recordingId=resp.get_return();
		
		// You may need to wait for a while for the audio to be downlaod and processed.
		Thread.sleep(10000);
		
		// attach a human transcription
		url=getBaseURL("attachHumanTranscription")+"&recordingId="+recordingId+"&humanTranscribed="+URLEncoder.encode("a number of method, including lean, that we can acutally", "UTF-8");
		result=get(url);
		AttachHumanTranscriptionResponse resp1=SearchService2Stub.AttachHumanTranscriptionResponse.Factory.parse(toXMLStreamReader(result));		
		
		// You may need to wait for a while for the timestamping to be processed.
		Thread.sleep(10000);
	
		// obtain the time stamped human transcription:
		url=getBaseURL("getTimeStampedHumanTranscription")+"&recordingId="+recordingId;
		result=get(url);
		SearchService2Stub.GetTimeStampedHumanTranscriptionResponse resp2=SearchService2Stub.GetTimeStampedHumanTranscriptionResponse.Factory.parse(toXMLStreamReader(result));
				
				
	}
	
	/**
	 * Util method
	 * @param action
	 * @return
	 */
	private static String getBaseURL(String action){
		return "https://api.nexiwave.com/services/"+action+"?authData.email="+"<youremail@email.com>"+"&authData.passwd="+"XXX";
	}

	/**
	 * Util method
	 * @param url
	 * @return
	 * @throws Exception
	 */
	protected String get(String url)throws Exception{
		
		System.out.println("Invoking "+url);
		
		URL u=new URL(url);
		URLConnection conn=u.openConnection();
		InputStream in=conn.getInputStream();
		try{
			StringBuilder sb=new StringBuilder();
			byte[] buf=new byte[512];
			int len;
			while((len=in.read(buf))>=0){
				sb.append(new String(buf, 0, len));
			}
			
			System.out.println("Respionse: |"+sb+"|");
			return sb.toString();
		}
		finally{
			in.close();
		}
	}
	private static XMLStreamReader toXMLStreamReader(String s)throws Exception{
		XMLInputFactory factory=XMLInputFactory.newInstance();
		XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(s));
		
		return reader;
	}

}
