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.networkutils.ImageManager;
import fishrungames.networkutils.UniversalActionWithCallback;
import fishrungames.networkutils.interfaces.RemoveCallbackInterface;
import fishrungames.networkutils.interfaces.UpdateAndFinishCallbackInterface;
import fishrungames.bashgid.core.NewsSearchRunnable;
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.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 UpdateAndFinishCallbackInterface
{

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

	volatile boolean searchIsPerformingNow = false;
	
	//NewsSearchRunnable nextSearchRunnable = null;
	
	boolean restorePreviousSearch = false;
	
	RemoveCallbackInterface removeCallback = null;
	Object removeCallbackSynchronizer = new Object();
	
	public SearchFragment()
	{
	}
	
	public SearchFragment(boolean restorePreviousSearch)
	{
		this.restorePreviousSearch = restorePreviousSearch;
	}
	
	@SuppressLint("InflateParams") @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;
	}
	
	@Override
	public void onDestroyView()
	{
		synchronized (removeCallbackSynchronizer)
    	{
    	if (removeCallback != null)
    	{
    		removeCallback.RemoveCallback();
    		removeCallback = null;
    	}
    	}
		super.onDestroyView();
	}
	
	
	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.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 OnFinished()
	{
		synchronized (removeCallbackSynchronizer)
    	{
			removeCallback = null;
    	}
		
	}

	@Override
	public void OnUpdated(Bundle result)
	{		
		getActivity().runOnUiThread(new RefreshSearchListRunnable());
	}
	
	public void CallUpdateNews(String text)
	{
		Bundle query = new Bundle();
		
		query.putString("query", text);
		
		removeCallback = UniversalActionWithCallback.PerformAction(new NewsSearchRunnable(), query, this, "NewsSearchRunnable");

	}
		
	private class RefreshSearchListRunnable implements Runnable
	{
		
		@Override
		public void run()
		{
			searchResultArr = NewsManager.getInstance().getSearchResultNews();
			
			listAdapter.notifyDataSetChanged();
			
		}
		
	}
	
	
	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);
		}
		
	}
	
	
}
