package it.unipr.mobdev.youtube;

import java.io.InputStream;
import java.net.URL;

import it.unipr.mobdev.R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class VideoDetailActivity extends Activity{

	private String title = null;
	private String thumbnail = null;
	private Drawable videoDrawable = null;
	
	//Handler definition. Allow to execute target methods or specific code on the main thread
	private final Handler handler = new Handler();
	
	private TextView videoTitleTextView = null;
	private ProgressBar progressBar = null;
	private ImageView videoImage = null;
	private Button openButton = null;
	private String playerUrl  = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.video_detail);
		
		Bundle bundle = this.getIntent().getExtras();
		title = bundle.getString("title");
		thumbnail  = bundle.getString("thumbnail");
		playerUrl   = bundle.getString("playerUrl");
		
		if(videoDrawable == null && title != null && thumbnail != null)
			init();
	}
	
	private void init()
	{
		progressBar  = (ProgressBar)findViewById(R.id.progressBar);
		videoTitleTextView  = (TextView)findViewById(R.id.titleTextView);
		videoImage   = (ImageView)findViewById(R.id.previewImage);
		openButton  = (Button)findViewById(R.id.openButton);
		
		videoTitleTextView.setText(title);
		
		openButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setData(Uri.parse(playerUrl));
				startActivity(i);
			}
		});
		
		//Dedicated thread to download the image associated to the selected video
		Thread imageDownload = new Thread(new Runnable() {
			@Override
			public void run() {
				
				Log.d(MainActivity.TAG, "Downloading Video Image ...");
				
				videoDrawable = null;
				
				try {
					
					//Open an input stream to a remote URL 
					InputStream is = (InputStream) new URL(thumbnail).getContent();
					
					//Method of Drawable class to automatically download and create an image from a Stream
					videoDrawable = Drawable.createFromStream(is, "image");
				
				} catch (Exception e) {
					e.printStackTrace();
				}

				if(videoDrawable != null)
				{
					//Handler user to update the main UI from a different Thread
					handler.post(new Runnable() {
						@Override
						public void run() {
							videoImage.setImageDrawable(videoDrawable);
							videoImage.setVisibility(View.VISIBLE);
							progressBar.setVisibility(View.INVISIBLE);
						}
					});
				}
			}
		});
		imageDownload.start();
	}

}
