package com.j0h1.contour;

import java.util.List;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.j0h1.contour.R;
import com.j0h1.contour.database.ContourDatabase;
import com.j0h1.contour.pojo.ImagePojo;
import com.j0h1.contour.pojo.ImageResponseList;
import com.j0h1.contour.pojo.Player;
import com.j0h1.contour.utils.RESTConfig;
import com.j0h1.contour.volley.SimpleXmlRequest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Window;
import android.widget.Toast;

public class TrackSessionLoadingActivity extends Activity {
	
	private ProgressDialog progressDialog;
	private Toast toast;
	protected String language;
	protected int trackId;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		// extract trackId from Intent
		Intent intent = getIntent();
		language = intent.getStringExtra("language");
		String trackIdString = intent.getStringExtra("trackId");
		trackId = Integer.valueOf(trackIdString);
		
		new LoadViewTask().execute();
	}

	/**
	 * Background task that executes the session upload.
	 */
	private class LoadViewTask extends AsyncTask<Void, Integer, Void> {
		@Override
		protected void onPreExecute() {
			// create and set up progress dialog
			progressDialog = new ProgressDialog(TrackSessionLoadingActivity.this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setTitle(getString(R.string.loading_data) + "...");
			progressDialog
					.setMessage(getString(R.string.requesting_images) + "...");
			progressDialog.setCancelable(false);
			progressDialog.setIndeterminate(true);
			progressDialog.show();
		}

		// the code to be executed in a background thread
		@Override
		protected Void doInBackground(Void... params) {			
			// get the current thread's token
			synchronized (this) {
				RequestQueue requestQueue = 
						Volley.newRequestQueue(TrackSessionLoadingActivity.this);
				
				// request edge images from selected Track
				SimpleXmlRequest<ImageResponseList> request = new SimpleXmlRequest<ImageResponseList>(
						Request.Method.GET,
						RESTConfig.BASE_URL + "images/track/" + trackId + "/language/" + language,
						ImageResponseList.class,
						new Response.Listener<ImageResponseList>() {
							@Override
							public void onResponse(ImageResponseList response) {
								if (response.getList() != null) {
									List<ImagePojo> edgeImages = response.getList();
									
									persistEdgeImagesAndStartSession(trackId, edgeImages);
								} else {
									prepareToast(getString(R.string.receiving_images_failed));
									toast.show();
								}
							}
						}, new Response.ErrorListener() {
							@Override
							public void onErrorResponse(VolleyError error) {
								prepareToast(getString(R.string.connection_lost));
								toast.show();
							}
						});
				
				requestQueue.add(request);
			}
			
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			progressDialog.setProgress(values[0]);
		}
		
		@Override
		protected void onPostExecute(Void result) {			
		}
	}
	
	/**
	 * Stores the edge images for this track in the local database and 
	 * starts a new session.
	 * @param trackId		TrackId of selected Track.
	 * @param edgeImages	Edge images of the selected track.
	 */
	private void persistEdgeImagesAndStartSession(int trackId, List<ImagePojo> edgeImages) {
		ContourDatabase db = new ContourDatabase(TrackSessionLoadingActivity.this);
		Player player = db.findPlayer();		
		// persist data needed to start a new session
		db.startTrackSession(player.getPlayerId(), trackId, edgeImages);		
		db.close();
		
		// start GameActivity
		Intent intent = new Intent(TrackSessionLoadingActivity.this, GameActivity.class);
		intent.putExtra("NewOrExistingSession", "newSession");
		intent.putExtra("GameMode", "track");
		startActivity(intent);
	}
	
	/**
	 * The activity handles the orientation changes itself, so on every orientation
	 * change (portrait to landscape and vice versa) this method is called.
	 */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    }
	
	@SuppressLint("ShowToast") 
	private void prepareToast(String message) {
		if (toast != null) {
    		toast.cancel();
    	}
    	toast = Toast.makeText(TrackSessionLoadingActivity.this, 
    			message, Toast.LENGTH_SHORT);
	}

}
