package fishrungames.bashgid.core;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import fishrungames.bashgid.MainActivity;
import fishrungames.bashgid.core.ArticleManager.ArticleShortData;

public class DatabaseSearchArticleTask extends AsyncTask<Bundle, Integer, Long>
{

	public Handler mHandler;

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

	ArrayList<String> translationNamesArr = new ArrayList<String>();

	protected Long doInBackground(Bundle... queryArr)
	{
		String query = queryArr[0].getString("query");

		String journalName = queryArr[0].getString("journalName");

		query = query.toUpperCase(Locale.getDefault());

		if (Locale.getDefault().equals(new Locale("ru")))
		{

			translationNamesArr = MainActivity.getInstance().translationDataSource.SearchRussian(query);
		} else if (Locale.getDefault() == Locale.CHINA)
		{
			translationNamesArr = MainActivity.getInstance().translationDataSource.SearchChinese(query);
		} else
		{
			translationNamesArr = MainActivity.getInstance().translationDataSource.SearchEnglish(query);
		}

		if (journalName != null && journalName.length() > 0)
		{
			for (String translationName : translationNamesArr)
			{
				articleArr.addAll(MainActivity.getInstance().articleDataSource.SearchArticleByTitleOrTextInJournal(translationName, journalName));
			}
		} else
		{
			for (String translationName : translationNamesArr)
			{
				articleArr.addAll(MainActivity.getInstance().articleDataSource.SearchArticleByTitleOrText(translationName));
			}
		}

		// Remove duplicates

		Set<ArticleShortData> articleSet = new TreeSet<ArticleShortData>(new Comparator<ArticleShortData>()
		{

			@Override
			public int compare(ArticleShortData lhs, ArticleShortData rhs)
			{
				return lhs.name.compareTo(rhs.name);
			}
		});

		articleSet.addAll(articleArr);

		articleArr.clear();

		articleArr.addAll(articleSet);

		return (long) 0;
	}

	protected void onProgressUpdate(Integer... progress)
	{
		Message completeMessage = mHandler.obtainMessage(MainActivity.DATABASE_SEARCH_ARTICLE_STATE_UPDATE, articleArr);

		completeMessage.sendToTarget();

	}

	protected void onPostExecute(Long result)
	{
		Message completeMessage = mHandler.obtainMessage(MainActivity.DATABASE_SEARCH_ARTICLE_STATE_FINISHED, articleArr);

		completeMessage.sendToTarget();
	}

}