package it.unipr.mobdev.youtube;

import it.unipr.mobdev.R;
import it.unipr.mobdev.youtube.remote.RESTRequest;
import it.unipr.mobdev.youtube.remote.RESTRequestExecutor;

import java.util.ArrayList;
import java.util.List;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import android.app.ListActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends ListActivity {

	public static String TAG = "MobDevYouTube";

	private TextView searchField = null;
	private final Handler handler = new Handler();
	private ArrayList<VideoDescriptor> videoList = null;
	
	//private static final int NOTIFICATION_ID = 1;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		searchField = (TextView)findViewById(R.id.searchField);

		//Setup the list view and its listener
		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				Bundle bundle = new Bundle();
				bundle.putString("title",videoList.get(position).getTitle());
				bundle.putString("thumbnail",videoList.get(position).getThumbnail());
				bundle.putString("playerUrl",videoList.get(position).getPlayerUrl());

				Intent newIntent = new Intent(getApplicationContext(), VideoDetailActivity.class);
				newIntent.putExtras(bundle);
				startActivity(newIntent);
			}

		});

		//Setup the search button and its listener
		Button searchButton = (Button)findViewById(R.id.searchButton);
		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d(TAG, "Search Artist ...");

				String searchInputString = searchField.getText().toString();

				if( searchInputString != null && searchInputString.length() > 0)
				{
					try {
						String requestURL = String.format("https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&category=Music&orderby=relevance&q=%s",Uri.encode(searchInputString));
						Log.d(TAG,requestURL);
						DownloadYouTubeJSONData youtubeAsyncTask = new DownloadYouTubeJSONData();
						youtubeAsyncTask.execute(new String[] { requestURL });
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});

		if(videoList == null)
			videoList = new ArrayList<VideoDescriptor>();
		else
			updateVideoListView(videoList);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override  
	protected void onListItemClick(ListView l, View v, int position, long id) {  
		super.onListItemClick(l, v, position, id);  
	}  

	public void updateVideoListView(List<VideoDescriptor> values)
	{
		ArrayAdapter<VideoDescriptor> adapter = new ArrayAdapter<VideoDescriptor>(this,R.layout.list_item, values);
		setListAdapter(adapter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public void showToastMessage(final String message, final int length) {

		handler.post(new Runnable() {

			@Override
			public void run() {
				Toast toast = Toast.makeText(getApplicationContext(), message, length);
				toast.show();
			}
		});
	}
	
	/**
	 * Create a new Status Bar Notification associated to a new Video List retrieved
	 */
	public void createApplicationNotification()
	{
		// Prepare the intent triggered if the notification is selected
		Intent intent = new Intent(this, MainActivity.class);
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

		// Build the notification
		// Use NotificationCompat.Builder instead of just Notification.Builder to support older Android versions
		Notification n  = new NotificationCompat.Builder(this)
		        .setContentTitle("MobDev - YouTube App")
		        .setContentText("New Video List Available")
		        .setSmallIcon(R.drawable.icon_notification_exclamation_mark)
		        .setContentIntent(pIntent)
		        .setAutoCancel(true).build();
		    
		  
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager.notify(0, n); 
	}
	
	/*
	public void createApplicationNotification()
	{
		int icon = R.drawable.icon_notification_exclamation_mark;   // icon from resources
		CharSequence tickerText = "New Video List Available";       // ticker-text
		long when = System.currentTimeMillis();         // notification time
		CharSequence contentTitle = "ADSource 6 - YouTube";  // message title
		CharSequence contentText = "New Video List Available";      // message text

		Intent notificationIntent = new Intent(this, MainActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

		// the next two lines initialize the Notification, using the configurations above
		Notification notification = new Notification(icon, tickerText, when);
		notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent);
		notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
		
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		mNotificationManager.notify(NOTIFICATION_ID, notification);
	}
	*/
	
	/**
	 * Definition of the AsyncTask to download the list of YouTube Videos for a specific artist
	 * 
	 * @author Marco Picone
	 *
	 */
	private class DownloadYouTubeJSONData extends AsyncTask<String, Integer, Boolean>{

		private ProgressDialog mProgressDialog = null;

		private String remoteUrl = null;

		@Override
		protected void onCancelled() {
			Log.e(TAG,"AsyncTask->DownloadYouTubeJSONData: onCancelled !");
			super.onCancelled();
		}

		@Override
		protected void onPreExecute() {
			Log.d(TAG,"AsyncTask->DownloadYouTubeJSONData: onPreExecute !");

			//Progress Dialog Setup
			mProgressDialog  = new ProgressDialog(MainActivity.this);
			mProgressDialog.setMessage("Downloading YouTube Data ...");
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.setCancelable(false);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

			mProgressDialog.show();
			
			videoList.clear();

			super.onPreExecute();
		}

		@Override
		protected Boolean doInBackground(String... params) {

			if(params.length == 0)
				return false;
			else
				this.remoteUrl = params[0];
			
			Log.d(TAG,"AsyncTask->DownloadYouTubeJSONData: doInBackground ! ("+this.remoteUrl+")");
			
			//HTTP Request to retrieve the video list in JSON format
			try{

				//Creates the remote request
				RESTRequest request = new RESTRequest(this.remoteUrl);
				request.isMethodGET(true);

				//Executes the request and print the received response
				String response = RESTRequestExecutor.execute(request);

				
				//Custom/Manual parsing using GSON
				JsonParser parser = new JsonParser();

				if(response != null && response.length() > 0)
				{
					Log.d(TAG,"Response: " + response);
					JsonObject jsonObject = (JsonObject)parser.parse(response);

					JsonArray items = jsonObject.getAsJsonObject("data").getAsJsonArray("items");

					String id = null;
					String title = null;
					String thumbnail = null;
					String playerUrl = null;

					for(int index=0; index < items.size(); index++)
					{
						JsonObject itemObj = (JsonObject )items.get(index);
						id = itemObj.get("id").getAsString();
						title = itemObj.get("title").getAsString();
						thumbnail = ((JsonObject)itemObj.get("thumbnail")).get("hqDefault").getAsString();
						playerUrl = ((JsonObject)itemObj.get("player")).get("default").getAsString();
						videoList.add(new VideoDescriptor(id,title,thumbnail,playerUrl));
					}
					
					return true;
				}
				else
				{
					Log.d(TAG,"Error getting response ...");
					return false;
				}

			}
			catch (Exception e) {
				e.printStackTrace();
				Log.e(TAG,"Exception: " + e.getLocalizedMessage());
			}
			
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			Log.d(TAG,"AsyncTask->DownloadYouTubeJSONData: onPostExecute !");

			if(mProgressDialog != null)
				mProgressDialog.dismiss();

			if(result == false)
			{
				Log.e(TAG,"AsyncTask->DownloadYouTubeJSONData: Error Downloading YouTube Data !");
				showToastMessage("Error Downloading Locations !", Toast.LENGTH_LONG);
			}
			else
			{
				Log.d(TAG,"AsyncTask->DownloadYouTubeJSONData: YouTubeData Correctly Downloaded !");

				createApplicationNotification();
				
				if(videoList != null && videoList.size() > 0)
					updateVideoListView(videoList);
			}

			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {

			//Update the progress dialog and the associated progress bar
			if(mProgressDialog != null && values != null && values.length == 2)
			{
				if(values[0] == 0)
				{
					mProgressDialog.setMessage("Loading YouTube Data ...");
					mProgressDialog.setIndeterminate(false);
					mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					mProgressDialog.setMax(100);
				}
				else
				{
					double value = 100.0*(double)((double)values[0]/(double)values[1]);
					mProgressDialog.setProgress((int) value);
				}
			}

			super.onProgressUpdate(values);
		}

	}
}