package ReadRS;

import gr.uoa.di.madgik.grs.buffer.IBuffer.Status;
import gr.uoa.di.madgik.grs.reader.ForwardReader;
import gr.uoa.di.madgik.grs.reader.IRecordReader;
import gr.uoa.di.madgik.grs.record.Record;
import gr.uoa.di.madgik.grs.record.field.Field;
import gr.uoa.di.madgik.grs.record.field.StringField;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;
import java.net.URI;

import org.gcube.common.searchservice.searchlibrary.resultset.elements.ResultElementGeneric;
import org.gcube.common.searchservice.searchlibrary.rsclient.elements.RSLocator;
import org.gcube.common.searchservice.searchlibrary.rsclient.elements.RSResourceLocalType;
import org.gcube.common.searchservice.searchlibrary.rsreader.RSXMLIterator;
import org.gcube.common.searchservice.searchlibrary.rsreader.RSXMLReader;


public class ReadRS {

	public static void main(String[] args) {
		try {
			if(args.length!=1)
				System.out.println("locator filename needed");
			readRS(readTextFile(args[0]));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static String readTextFile(String filename) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));
		StringBuffer buf = new StringBuffer();
		String tmp;
		while ((tmp = br.readLine()) != null) {
			buf.append(tmp + "\n");
		}
		br.close();
		return buf.toString();
	}
	
	private static void readRS(final String locator) {
		try {
			int rc = 0;
			
			IRecordReader<Record> reader = new ForwardReader<Record>(new URI(locator.trim()));
			while(true) {
				
				if(reader.getStatus() == Status.Dispose || (reader.getStatus()==Status.Close && reader.availableRecords()==0))
					break;
				
				Record rec = reader.get(200, TimeUnit.SECONDS);
				if(rec == null) {
					if(reader.getStatus() == Status.Open) 
						System.err.println("Producer has timed out");
					break;
				}
				
				rc++;
				System.out.print("Record #" + rc + " : ");
				
				for(Field f : rec.getFields()) {
						System.out.print(rec.getDefinition().getDefinition(f.getDefinitionIndex()).getName() + "=");
						if(f instanceof StringField) {
							System.out.print(((StringField)f).getPayload());
						//	System.out.println("Payload size: " + ((StringField)f).getPayload().length() + " chars");
						}
						else
							System.out.print(f.getClass().getName().toUpperCase());
						System.out.println(" ");
				}
				System.out.println();
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
