package fishrungames.bashgid;

import java.util.ArrayList;
import java.util.Locale;

import fishrungames.bashgid.core.ArticleManager.ArticleShortData;

import fishrungames.bashgid.core.DatabaseSearchArticleTask;

import fishrungames.networkutils.ImageManager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;

import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;

import android.widget.EditText;

import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SearchFragment extends Fragment
{

	ListView listView;

	ListAdapter listAdapter;

	TextView hintTextView;

	EditText searchEditText;

	ArrayList<ArticleShortData> searchResultArr = new ArrayList<ArticleShortData>();

	String journalName;
	String journalTitle;
	String query;

	DatabaseSearchArticleTask databaseSearchArticleTask = null;

	public SearchFragment()
	{
		this.journalName = "";
		this.journalTitle = "";
		this.query = "";
	}

	public SearchFragment(String query)
	{
		this.journalName = "";
		this.journalTitle = "";
		this.journalTitle = "";
		this.query = query;
	}

	public SearchFragment(String journalName, String journalTitle)
	{
		this.journalName = journalName;
		this.journalTitle = journalTitle;
		this.query = "";
	}
	
	public SearchFragment(String query, String journalName, String journalTitle)
	{
		this.journalName = journalName;
		this.journalTitle = journalTitle;
		this.query = query;
	}

	@Override
	public void onSaveInstanceState(final Bundle outState)
	{
		super.onSaveInstanceState(outState);
		outState.putString("journalName", journalName);
		outState.putString("journalTitle", journalTitle);
		outState.putString("query", query);
	}

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

		if (savedInstanceState != null)
		{
			journalName = savedInstanceState.getString("journalName");
			journalTitle = savedInstanceState.getString("journalTitle");
			query = savedInstanceState.getString("query");

		}

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

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

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

		TextView addressTextView = (TextView) header.findViewById(R.id.addressTextView);

		if (journalTitle == null || journalTitle.length() == 0)
		{
			addressTextView.setText(R.string.search_everywhere);
		} else
		{
			String search_in = this.getResources().getString(R.string.search_in);

			search_in = search_in.replace("%%", journalTitle);

			addressTextView.setText(search_in);
		}

		hintTextView = (TextView) header.findViewById(R.id.hintTextView);

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

		searchEditText.setText(query);

		searchEditText.addTextChangedListener(new TextWatcher()
		{

			public void afterTextChanged(Editable s)
			{

				query = searchEditText.getText().toString();

				CallUpdateNews();

			}

			public void beforeTextChanged(CharSequence s, int start, int count, int after)
			{
			}

			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
			}
		});

		listView.addHeaderView(header);

		listAdapter = new ListAdapter(getActivity());

		listView.setAdapter(listAdapter);

		listView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				
				MainActivity.getInstance().SetLastJournalName(journalName);
				MainActivity.getInstance().SetLastJournalTitle(journalTitle);
				
				MainActivity.getInstance().SetLastSearchQuery(query);
				MainActivity.getInstance().OpenArticleScreen(searchResultArr.get(position - 1).name, MainActivity.TAG_BACK_TO_SEARCHFRAGMENT);
			}
		});

		CallUpdateNews();

		return rootView;
	}

	public void SetSearchResult(ArrayList<ArticleShortData> articleArr)
	{
		searchResultArr = articleArr;
		listAdapter.notifyDataSetChanged();

		String searchResultCount = getResources().getString(R.string.search_result_count);

		searchResultCount = searchResultCount.replace("%%", Integer.toString(articleArr.size()));

		hintTextView.setText(searchResultCount);
	}

	public class ListAdapter extends BaseAdapter
	{
		private Context mContext;

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

		public int getCount()
		{
			return searchResultArr.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.journal_element, null);

			} else
			{
				view = convertView;
			}

			TextView titleTextView = (TextView) view.findViewById(R.id.titleTextView);

			titleTextView.setText(searchResultArr.get(position).title);

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

			dateTextView.setText(MainActivity.iso8601Format.format(searchResultArr.get(position).dateTime));

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

			if (searchResultArr.get(position).previewImageUrl != null)
			{
				ImageManager.getInstance().ApplyImageToImageView(imageView, searchResultArr.get(position).previewImageUrl);
			} else
			{
				imageView.setImageResource(R.drawable.transparent);
			}
			return view;
		}

	}

	public void CallUpdateNews()
	{

		if (query.length() >= 3 || Locale.getDefault() == Locale.CHINA)
		{
			if (databaseSearchArticleTask != null)
			{
				databaseSearchArticleTask.cancel(false);
			}

			databaseSearchArticleTask = new DatabaseSearchArticleTask();

			databaseSearchArticleTask.mHandler = MainActivity.getInstance().mHandler;

			Bundle bundle = new Bundle();

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

			databaseSearchArticleTask.execute(bundle);

			hintTextView.setText(R.string.search_is_performing);
		} else
		{
			searchResultArr.clear();
			listAdapter.notifyDataSetChanged();

			hintTextView.setText(R.string.search_at_least_3_symbols);
		}
	}

}
