package fishrungames.bashgid.core;

import java.util.concurrent.Semaphore;


import android.util.Log;

public class NewsSearchRunnable implements Runnable, RemoveCallbackInterface
{
	
	private volatile Semaphore callbackMutex = new Semaphore(1, true);
	
	private NewsUpdatedCallbackInterface callback = null;
	
	private String query;
	
	public NewsSearchRunnable(NewsUpdatedCallbackInterface callback, String query)
	{
		this.query = query;
		
		try
		{
			callbackMutex.acquire();
			try
			{		
			
				this.callback = callback;
				
				
			} finally
			{
				callbackMutex.release();
			}
		} catch (InterruptedException ie)
		{
			Log.e("Error in NewsSearchRunnable", "Error in NewsSearchRunnable");
		}
	}

	@Override
	public void run()
	{
		
		NewsManager.GetInstance().searchNews(query);
		
		//After all
		
		try
		{
			callbackMutex.acquire();
			try
			{		
			
				if (callback != null)
				{
					callback.OnNewsUpdated();
					
					callback = null;
				}
				
			} finally
			{
				callbackMutex.release();
			}
		} catch (InterruptedException ie)
		{
			Log.e("Error in DownloadNewsRunnable", "Error in DownloadNewsRunnable");
		}
	}

	@Override
	public void RemoveCallback()
	{
		try
		{
			callbackMutex.acquire();
			try
			{		
			
				callback = null;
				
			} finally
			{
				callbackMutex.release();
			}
		} catch (InterruptedException ie)
		{
			Log.e("Error in NewsSearchRunnable", "Error in NewsSearchRunnable");
		}
	}

}
