package org.physionet.challenge2011;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class ChallengeScoreActivity extends ChallengeActivity implements Runnable {
	/** Called when the activity is first created. */

	private static final String header_file="ecg_header";
	private static final int N=50; // should match number of rows in the /raw/ecg_header.txt file
	private TextView mTimeLabel;
	public static final String TAG = ChallengeScoreActivity.class.toString();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.score);

		// Handle Start button
		final Button startButton = (Button) findViewById(R.id.Button_Start);
		Button exitButton = (Button) findViewById(R.id.Button_Exit);
		mTimeLabel = (TextView) findViewById(R.id.ResultText);
		mTimeLabel.setText("Ready");
		final Thread thread = new Thread(this);

		startButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				mTimeLabel.setText("Running...");
				startButton.setEnabled(false);
				thread.start();
			}
		});	

		exitButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});


	}


	private Handler mHandler = new Handler(){
		public void handleMessage(Message msg){
			mTimeLabel = (TextView) findViewById(R.id.ResultText);
			if(msg.what != N){
				String tmp= "File " + msg.what + " of " + N + " \n" + msg.getData().getString("rkey"); 
				mTimeLabel.setText(tmp);
			}else{
				mTimeLabel.setText("Finished!!");	
			}

		}
	};	

	public void run(){

		ChallengeEntry code= new ChallengeEntry();
		Resources r = getResources();
		int result = -1;
		double elapsed_time=0;
		long start_time=0, end_time=0, trial_time=0;
		int data_int, xml_int, i=1;
		InputStream HiFile = getResources().openRawResource(r.getIdentifier(header_file,"raw", "org.physionet.challenge2011"));
		InputStreamReader inread= new InputStreamReader(HiFile);
		BufferedReader buf = new BufferedReader(inread,500);
		String strLine=null;
		ECG_MetaData m_MetaData= null;
		
		
		try {
			strLine = buf.readLine();
		} catch (IOException e1) {
			Log.w(TAG,"Could not read ecg header file: " + header_file);
		}
		
		
		while (strLine != null){
			data_int = r.getIdentifier(strLine,"raw", "org.physionet.challenge2011");
			
			//Get Meta Data for the file
			xml_int=r.getIdentifier(strLine,"xml", "org.physionet.challenge2011");
			InputStream iFile = getResources().openRawResource(data_int);
			XmlPullParser mparser = getResources().getXml(xml_int);
			
			Log.w(TAG,"Data and xml metadata  file is : " + strLine);
			try {
				Log.w(TAG," Getting metadata.");
				m_MetaData= ECGXmlParser.Parse(mparser,new ECG_MetaData());
				Log.w(TAG," Done getting metadata. Age is " + m_MetaData.age);
			} catch (XmlPullParserException e2) {
				Log.e(TAG,"Could not parse file: " + strLine);
				e2.printStackTrace();
			} catch (IOException e2) {
				Log.e(TAG,"Could not open xml file: " + strLine);
			}
			
			
			try {
				start_time=System.currentTimeMillis();
				result=code.get_result(iFile,m_MetaData);
				end_time=System.currentTimeMillis();
			} catch (IOException e) {
				Log.e(TAG,"Exception while getting results for file " + strLine);
				e.printStackTrace();
				finish();
			}
			trial_time=end_time-start_time;
			elapsed_time +=  ((double) trial_time/1000);
			Message msg = new Message();
			msg.what=i;
			Bundle mBundle= new Bundle();
			mBundle.putString("rkey","Total time (s)= " + (long) elapsed_time + 
					" \nTrial time (ms): " + trial_time + 
					" \nFile Name: " + strLine +
					" \nAge: " + m_MetaData.age +
					" \nSex: " + m_MetaData.sex +
					" \nQuality: " + result);
			msg.setData(mBundle);
			mHandler.sendMessageAtTime(msg,0);
			i++;
			try {
				strLine = buf.readLine();
			} catch (IOException e1) {
				Log.w(TAG,"Could read ecg header file: " + header_file);
			}
		}
	}

}