package fishrungames.bashgid;

import java.util.ArrayList;

import fishrungames.bashgid.core.DatabaseDownloadTask;
import fishrungames.bashgid.core.DatabaseGetJournalListTask;
import fishrungames.bashgid.core.DatabaseGetJournalTask;
import fishrungames.bashgid.core.JournalManager;
import fishrungames.bashgid.core.NewsDownloadTask;

import fishrungames.bashgid.core.JournalManager.JournalSemiFullData;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import it.sephiroth.android.library.widget.HListView;

public class MainPageFragment extends Fragment
{

	ArrayList<JournalSemiFullData> journalList = new ArrayList<JournalSemiFullData>();

	ListView listView;
	ListAdapter listAdapter;
	View header;
	ProgressBar newsDownloadProgressBar;
	ProgressBar databaseDownloadProgressBar;
	EditText searchEditText;

	JournalSemiFullData newsJournal = JournalManager.CreateEmptyJournalSemiFull();

	DatabaseGetJournalTask databaseGetJournalTask = null;
	DatabaseGetJournalListTask databaseGetJournalListTask = null;

	public MainPageFragment()
	{
	}

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

		View rootView = inflater.inflate(R.layout.fragment_main_page, container, false);

		listView = (ListView) rootView.findViewById(R.id.listView);

		listAdapter = new ListAdapter(getActivity());

		header = inflater.inflate(R.layout.main_page_header, null);

		listView.addHeaderView(header);

		listView.setAdapter(listAdapter);

		newsDownloadProgressBar = (ProgressBar) header.findViewById(R.id.newsDownloadProgressBar);

		newsDownloadProgressBar.setVisibility(View.VISIBLE);
		
		newsDownloadProgressBar.setProgress(BashgidApplication.GetNewsDownloadProgress());
		
		databaseDownloadProgressBar = (ProgressBar) header.findViewById(R.id.databaseDownloadProgressBar);

		databaseDownloadProgressBar.setVisibility(View.VISIBLE);
		
		databaseDownloadProgressBar.setProgress(BashgidApplication.GetDatabaseDownloadProgress());

		Button moreNewsButton = (Button) header.findViewById(R.id.moreNewsButton);

		moreNewsButton.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				MainActivity.getInstance().OpenNewsScreen(false);
			}
		});

		searchEditText = (EditText) header.findViewById(R.id.searchEditText);

		Button searchButton = (Button) header.findViewById(R.id.searchButton);

		searchButton.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				String query = searchEditText.getText().toString();
				MainActivity.getInstance().OpenSearchScreen(query);
			}
		});
		
		searchEditText.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event)
			{
				if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
			            (keyCode == KeyEvent.KEYCODE_ENTER)) {
					String query = searchEditText.getText().toString();
					MainActivity.getInstance().OpenSearchScreen(query);
			          return true;
			        }
			        return false;
			}
		});
		
		ImageButton refreshCatalogButton = (ImageButton) header.findViewById(R.id.refreshCatalogButton);

		refreshCatalogButton.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				BashgidApplication.CancelDownloadDatabaseTask();
				BashgidApplication.DownloadDatabase();
			}
		});
		
		ImageButton refreshNewsButton = (ImageButton) header.findViewById(R.id.refreshNewsButton);
		
		refreshNewsButton.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				BashgidApplication.CancelDownloadNewsTask();
				BashgidApplication.StartDownloadNewsTask();
			}
		});
		

		RestoreJournalListFromDatabase();
		RestoreNewsFromDatabase();
		BashgidApplication.StartDownloadNewsTask();
		BashgidApplication.DownloadDatabase();
		
		return rootView;
	}

	@Override
	public void onDestroyView()
	{
		CancelRestoreNewsTaskIfRunning();
		CancelRestoreJournalListTasksIfRunning();

		super.onDestroyView();
	}

	public void CancelRestoreNewsTaskIfRunning()
	{
		if (databaseGetJournalTask != null)
		{
			databaseGetJournalTask.cancel(false);
			databaseGetJournalTask = null;
		}

	}

	public void CancelRestoreJournalListTasksIfRunning()
	{
		if (databaseGetJournalListTask != null)
		{
			databaseGetJournalListTask.cancel(false);
			databaseGetJournalListTask = null;
		}
	}
	
	public void RestoreNewsFromDatabase()
	{
		CancelRestoreNewsTaskIfRunning();

		databaseGetJournalTask = new DatabaseGetJournalTask();

		//databaseGetJournalTask.mHandler = MainActivity.getInstance().databaseHandler;

		Bundle bundle = new Bundle();

		bundle.putString("journalName", "news");

		bundle.putInt("count", 3);

		databaseGetJournalTask .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, bundle);
	}

	public void OnNewsDownloadProgress(Integer percent)
	{
		
		newsDownloadProgressBar.setProgress(percent);
		
		if (percent >= 100)
		{
			newsDownloadProgressBar.setVisibility(View.GONE);
		}
		else
		{
			newsDownloadProgressBar.setVisibility(View.VISIBLE);
		}
		
		if (databaseGetJournalTask == null || percent == 100)
		{
			RestoreNewsFromDatabase();
		}
		
		//RestoreNewsFromDatabase();
		
		//SetJournal(r.journal);
	
	}
	
	public void OnDatabaseDonwloadProgress(Integer percent)
	{
		databaseDownloadProgressBar.setProgress(percent);
		
		if (percent >= 100)
		{
			databaseDownloadProgressBar.setVisibility(View.GONE);
		}
		else
		{
			databaseDownloadProgressBar.setVisibility(View.VISIBLE);
		}
		
		if (databaseGetJournalListTask == null || percent == 100)
		{
			RestoreJournalListFromDatabase();
		}
		
		//SetJournalList(r.journalList);
	}
		

	void RestoreJournalListFromDatabase()
	{

		CancelRestoreJournalListTasksIfRunning();

		
		databaseGetJournalListTask = new DatabaseGetJournalListTask();

		//databaseGetJournalListTask.mHandler = MainActivity.getInstance().databaseHandler;

		databaseGetJournalListTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "featured");
		
	}

	public void SetJournal(JournalSemiFullData journal)
	{
		CancelRestoreNewsTaskIfRunning();

		newsJournal = journal;

		Button news1Button = (Button) header.findViewById(R.id.news1Button);
		Button news2Button = (Button) header.findViewById(R.id.news2Button);
		Button news3Button = (Button) header.findViewById(R.id.news3Button);

		if (newsJournal.articleArr.size() > 0)
		{

			news1Button.setText(newsJournal.articleArr.get(0).title);

			news1Button.setOnClickListener(new NewsButtonOnClickListener(newsJournal.articleArr.get(0).name));
		} else
		{

			news1Button.setText(R.string.news_record_not_available);

			news1Button.setOnClickListener(null);
		}

		if (newsJournal.articleArr.size() > 1)
		{

			news2Button.setText(newsJournal.articleArr.get(1).title);

			news2Button.setOnClickListener(new NewsButtonOnClickListener(newsJournal.articleArr.get(1).name));
		} else
		{

			news2Button.setText(R.string.news_record_not_available);
			news2Button.setOnClickListener(null);
		}

		if (newsJournal.articleArr.size() > 2)
		{

			news3Button.setText(newsJournal.articleArr.get(2).title);
			news3Button.setOnClickListener(new NewsButtonOnClickListener(newsJournal.articleArr.get(2).name));
		} else
		{

			news3Button.setText(R.string.news_record_not_available);
			news3Button.setOnClickListener(null);
		}

		listAdapter.notifyDataSetChanged();

	}

	public void SetJournalList(ArrayList<JournalSemiFullData> journalList)
	{
		databaseGetJournalListTask = null;

		this.journalList = journalList;

		listAdapter.notifyDataSetChanged();
	}

	public void RefreshAdapter()
	{
		if (listAdapter != null)
		{
			listAdapter.notifyDataSetChanged();
		}
	}

	public class ListAdapter extends BaseAdapter
	{
		private Context mContext;

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

		public int getCount()
		{
			return journalList.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(final 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.main_page_list_element, null);

			} else
			{
				view = convertView;
			}

			TextView textView = (TextView) view.findViewById(R.id.dateTextView);
			TextView descriptionTextView = (TextView) view.findViewById(R.id.descriptionTextView);

			Button button = (Button) view.findViewById(R.id.button);

			ImageButton imageButton = (ImageButton) view.findViewById(R.id.imageButton);

			HListView hListView = (HListView) view.findViewById(R.id.hListView);

			hListView.setAdapter(new MainPageHListViewAdapters.JournalElementAdapter(getActivity(), journalList.get(position)));

			textView.setText(journalList.get(position).title);

			if (journalList.get(position).description.length() > 0)
			{
				descriptionTextView.setText(journalList.get(position).description);

				descriptionTextView.setVisibility(View.VISIBLE);
			} else
			{
				descriptionTextView.setVisibility(View.GONE);
			}

			button.setText(R.string.see_all);

			button.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					if (databaseGetJournalTask != null)
					{
						databaseGetJournalTask.cancel(false);
					}
					MainActivity.getInstance().OpenJournalScreen(false, journalList.get(position).name, MainActivity.TAG_BACK_TO_MAINFRAGMENT);
				}
			});

			imageButton.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					if (databaseGetJournalTask != null)
					{
						databaseGetJournalTask.cancel(false);
					}
					MainActivity.getInstance().OpenJournalScreen(false, journalList.get(position).name, MainActivity.TAG_BACK_TO_MAINFRAGMENT);
				}
			});

			return view;
		}

	}

	public class NewsButtonOnClickListener implements OnClickListener
	{

		String articleName;

		public NewsButtonOnClickListener(String articleName)
		{
			this.articleName = articleName;
		}

		@Override
		public void onClick(View v)
		{
			if (databaseGetJournalTask != null)
			{
				databaseGetJournalTask.cancel(false);
				databaseGetJournalTask = null;
			}

			MainActivity.getInstance().OpenArticleScreen(articleName, MainActivity.TAG_BACK_TO_MAINFRAGMENT);

		}

	}

}
