package fishrungames.bashgid;



import fishrungames.bashgid.core.ChannelManager;
import fishrungames.bashgid.core.ChannelManager.ChannelFullData;

import fishrungames.networkutils.ImageManager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;

import android.widget.TextView;


public class VideoListFragment extends Fragment
{

	ListAdapter listAdapter;

	GridView gridView;
	ProgressBar progressBar;

	String channelName = "";
	ChannelFullData channelFullData = ChannelManager.CreateEmptyChannel();
	
	DatabaseGetChannelTask databaseGetChannelTask = null;
	
	public VideoListFragment()
	{
		this.channelName = "";
	}

	public VideoListFragment(String channelName)
	{
		this.channelName = channelName;
		RestoreChannel();
	}
	
	public VideoListFragment(ChannelFullData channelFullData)
	{
		this.channelName = channelFullData.name;
		this.channelFullData = channelFullData;
	}
	
	@Override
    public void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("channelName", channelName);
    }

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_grid_page, container, false);
		
		progressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
		
		progressBar.setVisibility(View.VISIBLE);


		gridView = (GridView) rootView.findViewById(R.id.gridView);

		listAdapter = new ListAdapter(getActivity());

		gridView.setAdapter(listAdapter);

		gridView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				
				BashgidApplication.SetLastChannelName(channelName);
				
				MainActivity.getInstance().OpenVideoRecordScreen(channelFullData.videoRecordArr.get(position));
			}

		});
		
		if (savedInstanceState != null) {
			channelName = savedInstanceState.getString("channelName");
			
        }
		
		if (channelName.length() > 0 && channelFullData.videoRecordArr.size() == 0)
		{
			RestoreChannel();
		}

		return rootView;
	}
	
	@Override
	public void onDestroyView()
	{
		CancelTaskIfRunning();
		
		super.onDestroyView();
	}
	
	public void OnDatabaseDonwloadProgress(Integer percent)
	{
		/*
		databaseDownloadProgressBar.setProgress(percent);
		
		if (percent >= 100)
		{
			databaseDownloadProgressBar.setVisibility(View.GONE);
		}
		else
		{
			databaseDownloadProgressBar.setVisibility(View.VISIBLE);
		}
		*/
		if (databaseGetChannelTask == null || percent == 100)
		{
			RestoreChannel();
		}
		
		//SetJournalList(r.journalList);
	}
	
	void RestoreChannel()
	{
		CancelTaskIfRunning();
		
		databaseGetChannelTask = new DatabaseGetChannelTask();

		//databaseGetChannelTask.mHandler = MainActivity.getInstance().mainHandler;

		databaseGetChannelTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, channelName);
	}
	
	void SetChannel(ChannelFullData channelFullData)
	{
		databaseGetChannelTask = null;
		
		progressBar.setVisibility(View.GONE);

		this.channelFullData = channelFullData;
		
		listAdapter.notifyDataSetChanged();
	}
	
	public void CancelTaskIfRunning()
	{
		if (databaseGetChannelTask != null)
		{
			databaseGetChannelTask.cancel(false);
			databaseGetChannelTask = null;
		}
	}
	
	public void RefreshAdapter()
	{
		if (listAdapter != null)
		{
			listAdapter.notifyDataSetChanged();
		}
	}
	
	
	public class DatabaseGetChannelTask extends AsyncTask<String, Integer, Long>
	{

		ChannelFullData channel = null;
		
		//public Handler mHandler;

		protected Long doInBackground(String... queryArr)
		{
			String channelName = queryArr[0];
			
			channel = BashgidApplication.channelDataSource.GetChannelFullData(channelName);
			
			return (long) 0;
		}

		protected void onProgressUpdate(Integer... progress)
		{
			Message completeMessage = BashgidApplication.mainHandler.obtainMessage(BashgidApplication.DATABASE_GET_CHANNEL_STATE_UPDATE, channel);

			completeMessage.sendToTarget();

		}

		protected void onPostExecute(Long result)
		{
			Message completeMessage = BashgidApplication.mainHandler.obtainMessage(BashgidApplication.DATABASE_GET_CHANNEL_STATE_FINISHED, channel);

			completeMessage.sendToTarget();
		}
	}

	
	public class ListAdapter extends BaseAdapter {
		private Context mContext;

		public ListAdapter(Context c) {
			mContext = c;
		}

		public int getCount() {
			return channelFullData.videoRecordArr.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		// create a new ImageView for each item referenced by the Adapter
		@SuppressLint("InflateParams")
		public View getView(int position, View convertView, ViewGroup parent) {


			View view;
			if (convertView == null) {  // if it's not recycled, initialize some attributes
				LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(R.layout.grid_page_list_element, null);


			} else {
				view = convertView;
			}

			ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
			TextView nameTextView = (TextView) view.findViewById(R.id.nameTextView);

			//ImageManager.getInstance().ApplyImageToImageView(imageView, channelFullData.videoRecordArr.get(position).previewImageUrl);
			
			
			if (channelFullData.videoRecordArr.get(position) != null)
			{
				ImageManager.getInstance().ApplySmallImageToImageView(imageView, channelFullData.videoRecordArr.get(position).previewImageUrl);

				nameTextView.setText(channelFullData.videoRecordArr.get(position).title);
			}
			else
			{
				ImageManager.getInstance().ApplySmallImageToImageView(imageView, "R.drawable.no_picture");
				nameTextView.setText("");
			}
			
			

			return view;
		}

	}
	
	
}
