package fishrungames.bashgid;


import java.util.ArrayList;

import fishrungames.bashgid.core.NewsManager;
import fishrungames.bashgid.core.NewsManager.NewsRecord;
import fishrungames.bashgid.core.db.NewsDataSource;
import fishrungames.bashgid.core.ImageManager;
import fishrungames.bashgid.core.NewsSearchRunnable;
import fishrungames.bashgid.core.NewsUpdatedCallbackInterface;
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.View.OnClickListener;
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.TextView;

public class SearchFragment extends Fragment implements NewsUpdatedCallbackInterface
{

	ListView listView;
	
	ListAdapter listAdapter;
	
	EditText searchEditText;
	
	ArrayList<NewsRecord> searchResultArr = new ArrayList<NewsRecord>();

	volatile boolean searchIsPerformingNow = false;
	
	NewsSearchRunnable nextSearchRunnable = null;
	
	boolean restorePreviousSearch = false;
	
	public SearchFragment()
	{
	}
	
	public SearchFragment(boolean restorePreviousSearch)
	{
		this.restorePreviousSearch = restorePreviousSearch;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			
		View rootView = inflater.inflate(R.layout.fragment_search_page, container, false);
		
		listView = (ListView) rootView.findViewById(R.id.listView);
		
		listAdapter = new ListAdapter(getActivity());
		
		listView.setAdapter(listAdapter);
				
		View header = inflater.inflate(R.layout.search_page_list_header, null);
		
		searchEditText = (EditText) header.findViewById(R.id.editText);
		
		if (restorePreviousSearch)
		{
			searchEditText.setText(NewsManager.GetInstance().getLastSearchQuery());
			searchResultArr = NewsManager.GetInstance().getSearchResultNews();
		}
		
		
		searchEditText.addTextChangedListener(new TextWatcher(){
	        
			public void afterTextChanged(Editable s) {

				String text = searchEditText.getText().toString();
				
				CallUpdateNews(text);
				
	        }
	        
	        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);

		return rootView;
	}
	
	
	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
	    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.search_page_list_element, null);
	        
	        } else {
	        	view = convertView;
	        }
	        
	        ImageButton imageButton = (ImageButton) view.findViewById(R.id.imageButton);
	        
	        Button button = (Button) view.findViewById(R.id.button);
	        
	        TextView textView = (TextView) view.findViewById(R.id.textView);
	        
	        ImageManager.getInstance().ApplyImageToImageView(imageButton, searchResultArr.get(position).imageId);
	        
	        button.setText(searchResultArr.get(position).title);
	        
	        textView.setText(NewsDataSource.iso8601Format.format(searchResultArr.get(position).pubDate));
	        
	        button.setOnClickListener(new ButtonOnClickListener(searchResultArr.get(position)));
	        
	        imageButton.setOnClickListener(new ButtonOnClickListener(searchResultArr.get(position)));
	        
	        return view;
	    }

	}


	@Override
	public void OnNewsUpdated()
	{		
		getActivity().runOnUiThread(new RefreshSearchListRunnable());
	}
	
	public void CallUpdateNews(String text)
	{
		if (!searchIsPerformingNow)
		{
			searchIsPerformingNow = true;
			
			NewsSearchRunnable runnable = new NewsSearchRunnable(this, text);
			
			ImmediateSearchNews(runnable);
		}
		else
		{
			nextSearchRunnable = new NewsSearchRunnable(this, text);
		}
	}
	
	private void ImmediateSearchNews(NewsSearchRunnable runnable)
	{
		Thread thread = new Thread(runnable);
		
		thread.start();
	}
	
	
	private class RefreshSearchListRunnable implements Runnable
	{
		
		@Override
		public void run()
		{
			searchResultArr = NewsManager.GetInstance().getSearchResultNews();
			
			listAdapter.notifyDataSetChanged();
			
			searchIsPerformingNow = false;
			
			if (nextSearchRunnable != null)
			{
				ImmediateSearchNews(nextSearchRunnable);
				
				nextSearchRunnable = null;
			}
		}
		
	}
	
	
	public static class ButtonOnClickListener implements OnClickListener
	{
		
		NewsRecord newsRecord;
		
		public ButtonOnClickListener(NewsRecord newsRecord)
		{
			this.newsRecord = newsRecord;
		}

		@Override
		public void onClick(View v)
		{
			MainActivity.getInstance().OpenNewsRecordScreen(newsRecord, MainActivity.TAG_FROM_SEARCHFRAGMENT_TO_NEWSRECORDFRAGMENT);
		}
		
	}
	
	
}
