package fishrungames.bashgid.core.db;


import java.text.ParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;


import fishrungames.bashgid.MainActivity;

import fishrungames.bashgid.core.AlbumManager.AlbumFullData;
import fishrungames.bashgid.core.ArticleManager;
import fishrungames.bashgid.core.ArticleManager.ArticleFullData;
import fishrungames.bashgid.core.ArticleManager.ArticleRecordData;
import fishrungames.bashgid.core.ArticleManager.ArticleShortData;
import fishrungames.bashgid.core.ChannelManager.ChannelFullData;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class ArticleDataSource
{

	private BashgidSqliteHelper dbHelper = null;

	
	
	public static class DateSortComparator implements Comparator<ArticleManager.ArticleRecordData> {
	    public int compare(ArticleManager.ArticleRecordData record1, ArticleManager.ArticleRecordData record2) {
	        return record2.dateTime.compareTo(record1.dateTime);
	    }
	}
	

	public ArticleDataSource(Context context, BashgidSqliteHelper dbHelper)
	{
		this.dbHelper = dbHelper;
	}

	public void CreateNewArticle(ArticleManager.ArticleRecordData recordData)
	{
		SQLiteDatabase database = dbHelper.getWritableDatabase();

		if (database != null)
		{

			try
			{
				ContentValues values = new ContentValues();

				values.put(BashgidSqliteHelper.COLUMN_NAME, recordData.name);
				values.put(BashgidSqliteHelper.COLUMN_TYPE, recordData.type);
				values.put(BashgidSqliteHelper.COLUMN_TITLE, recordData.title);
				values.put(BashgidSqliteHelper.COLUMN_CONTENT, recordData.content);
				values.put(BashgidSqliteHelper.COLUMN_GEOLAT, recordData.geoLat);
				values.put(BashgidSqliteHelper.COLUMN_GEOLON, recordData.geoLon);
				values.put(BashgidSqliteHelper.COLUMN_ADDRESS, recordData.address);
				values.put(BashgidSqliteHelper.COLUMN_PHONE, recordData.phone);
				values.put(BashgidSqliteHelper.COLUMN_EXTERNAL_LINK, recordData.externalLink);
				values.put(BashgidSqliteHelper.COLUMN_EXTERNAL_LINK_TEXT, recordData.externalLinkText);
				values.put(BashgidSqliteHelper.COLUMN_DATE_TIME, ArticleManager.iso8601Format.format(recordData.dateTime));
				values.put(BashgidSqliteHelper.COLUMN_HIDDEN, recordData.hidden);
				
				if (!innerIsArticleAlreadyExist(recordData.name, database))
				{
					database.insert(BashgidSqliteHelper.TABLE_ARTICLE, null, values);
				} else
				{
					database.update(BashgidSqliteHelper.TABLE_ARTICLE, values, BashgidSqliteHelper.COLUMN_NAME + " = " +"\"" + recordData.name +"\"", null);
				}

			} finally
			{
				dbHelper.close();
			}
		}

	}
	
	public boolean IsArticleAlreadyExist(String name)
	{
		boolean result = false;
		
		SQLiteDatabase database = dbHelper.getWritableDatabase();

		if (database != null)
		{

			try
			{
				result = innerIsArticleAlreadyExist(name, database);
			

			} finally
			{
				dbHelper.close();
			}
		}
		
		return result;

	}
	
	public void AddAlbumToArticle(String albumName, String articleName)
	{
		SQLiteDatabase database = dbHelper.getWritableDatabase();

		if (database != null)
		{

			try
			{
				ContentValues values = new ContentValues();

				values.put(BashgidSqliteHelper.COLUMN_ALBUM_NAME, albumName);
				values.put(BashgidSqliteHelper.COLUMN_ARTICLE_NAME, articleName);

				if (!innerAlbumArticleRelationAlreadyExist(albumName, articleName, database))
				{
					//Log.e("a", "aaa1");
					database.insert(BashgidSqliteHelper.TABLE_ALBUM_ARTICLE_RELATION, null, values);
					//Log.e("a", "aaa2");
				} 
				//Log.e("a", "aaa3");

			} finally
			{
				dbHelper.close();
			}
		}
	}
	
	public void AddChannelToArticle(String channelName, String articleName)
	{
		SQLiteDatabase database = dbHelper.getWritableDatabase();

		if (database != null)
		{

			try
			{
				ContentValues values = new ContentValues();

				values.put(BashgidSqliteHelper.COLUMN_CHANNEL_NAME, channelName);
				values.put(BashgidSqliteHelper.COLUMN_ARTICLE_NAME, articleName);

				if (!innerChannelArticleRelationAlreadyExist(channelName, articleName, database))
				{
					//Log.e("a", "aaa1");
					database.insert(BashgidSqliteHelper.TABLE_CHANNEL_ARTICLE_RELATION, null, values);
					//Log.e("a", "aaa2");
				} 
				//Log.e("a", "aaa3");

			} finally
			{
				dbHelper.close();
			}
		}
	}
	
	public ArticleFullData GetArticleFullData(String name)
	{
		ArticleFullData result = null;
		
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		
		if (database != null)
		{
			try
			{
				
				result = InnerGetArticleFullData(name, database);
				
				
			} finally
			{
				dbHelper.close();
			}
		}
		
		return result;
	}
	
	public ArticleFullData InnerGetArticleFullData(String name, SQLiteDatabase database)
	{
		ArticleFullData result = null;
	
				
				ArticleRecordData recordData = innerGetArticleByName(name, database);
				
				if (recordData != null)
				{
					
					result = new ArticleFullData(recordData);
					
					ArrayList<String> albumNameArr = innerGetAlbumNameArrInArticle(name, database);

					for (String albumName : albumNameArr)
					{
						result.albumArr.add(MainActivity.getInstance().albumDataSource.InnerGetAlbumFullData(albumName, database));
					}
					
					ArrayList<String> channelNameArr = innerGetChannelNameArrInArticle(name, database);

					for (String channelName : channelNameArr)
					{
						result.channelArr.add(MainActivity.getInstance().channelDataSource.InnerGetChannelFullData(channelName, database));
					}
					
					result.title = MainActivity.getInstance().translationDataSource.TryTranslateText(result.title, database);
					result.content = MainActivity.getInstance().translationDataSource.TryTranslateText(result.content, database);
					result.address = MainActivity.getInstance().translationDataSource.TryTranslateText(result.address, database);
					result.externalLink = MainActivity.getInstance().translationDataSource.TryTranslateText(result.externalLink, database);
					result.externalLinkText = MainActivity.getInstance().translationDataSource.TryTranslateText(result.externalLinkText, database);
					
					
					
				}
				
		
		return result;
	}
	
	
	public ArticleShortData GetArticleShortData(String name)
	{
		ArticleShortData result = null;
		
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		
		if (database != null)
		{
			try
			{
				
				result = InnerGetArticleShortData(name, database);
				
				
			} finally
			{
				dbHelper.close();
			}
		}
		
		return result;
	}
	
	public ArrayList<ArticleShortData> SearchArticleByTitleOrText(String query)
	{
		ArrayList<ArticleShortData> result = new ArrayList<ArticleShortData>();
		
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		
		if (database != null)
		{
			try
			{
				ArrayList<String> articleNameArr = InnerSearchArticleByTitleOrText(query, database);
				
				for (String articleName : articleNameArr)
				{
					result.add(InnerGetArticleShortData(articleName, database));
				}
				
			} finally
			{
				dbHelper.close();
			}
		}
		
		return result;
	}
	
	public ArrayList<ArticleShortData> SearchArticleByTitleOrTextInJournal(String query, String journalName)
	{
		ArrayList<ArticleShortData> result = new ArrayList<ArticleShortData>();
		
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		
		if (database != null)
		{
			try
			{
				ArrayList<String> articleNameArr = InnerSearchArticleByTitleOrText(query, database);
				
				for (String articleName : articleNameArr)
				{
					if (MainActivity.getInstance().journalDataSource.InnerArticleJournalRelationAlreadyExist(articleName, journalName, database))
					{
						result.add(InnerGetArticleShortData(articleName, database));
					}
				}
				
			} finally
			{
				dbHelper.close();
			}
		}
		
		return result;
	}

	public ArrayList<ArticleShortData> SearchArticleByQuery(String query)
	{
		ArrayList<ArticleShortData> result = new ArrayList<ArticleShortData>();
		
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		
		if (database != null)
		{
			try
			{
				result = InnerSearchArticleByQuery(query, database);
				
				
			} finally
			{
				dbHelper.close();
			}
		}
		
		return result;
	}
	
	public ArrayList<ArticleShortData> SearchArticleByQueryAndJournal(String query, String journalName)
	{
		ArrayList<ArticleShortData> result = new ArrayList<ArticleShortData>();
		
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		
		if (database != null)
		{
			try
			{
				
				ArrayList<ArticleShortData> intermediateResult = InnerSearchArticleByQuery(query, database);
				
				for (ArticleShortData article : intermediateResult)
				{
					if (MainActivity.getInstance().journalDataSource.InnerArticleJournalRelationAlreadyExist(article.name, journalName, database))
					{
						result.add(article);
					}
				}
				
				
			} finally
			{
				dbHelper.close();
			}
		}
		
		return result;
	}
	
	public ArrayList<ArticleShortData> InnerSearchArticleByQuery(String query, SQLiteDatabase database)
	{
		ArrayList<ArticleShortData> result = new ArrayList<ArticleShortData>();
		
	
				ArrayList<ArticleRecordData> recordDataArr = innerGetArticlesByQuery(query, database);
				
				for (int i = 0; i < recordDataArr.size(); i++)
				{
					ArticleShortData article = new ArticleShortData(recordDataArr.get(i));
					
					article.previewImageUrl = getPreviewImageUrlForArticle(recordDataArr.get(i).name, database);
					
					result.add(article);
				}
				

		return result;
	}
	
	
	public boolean InnerArticleIsHidden(String name, SQLiteDatabase database)
	{
		boolean result = false;
		
		Cursor cursor = database.query(BashgidSqliteHelper.TABLE_ARTICLE, new String[] { BashgidSqliteHelper.COLUMN_NAME },
				BashgidSqliteHelper.COLUMN_NAME + "=? AND " +BashgidSqliteHelper.COLUMN_HIDDEN + "=1", new String[] { name }, null, null, null, null);

		if (cursor != null)
		{
			if (cursor.getCount() > 0)
			{
				result = true;
			}
			
			cursor.close();
			cursor = null;
		} 
		
		return result;
	}
	
	
	
	public ArticleShortData InnerGetArticleShortData(String name, SQLiteDatabase database)
	{
		ArticleShortData result = null;
		
	
				ArticleRecordData recordData = innerGetArticleByName(name, database);
				
				if (recordData != null)
				{
					
					result = new ArticleShortData(recordData);
					
					result.previewImageUrl = getPreviewImageUrlForArticle(name, database);
					
					result.title = MainActivity.getInstance().translationDataSource.TryTranslateText(result.title, database);
					result.content = MainActivity.getInstance().translationDataSource.TryTranslateText(result.content, database);
					result.externalLink = MainActivity.getInstance().translationDataSource.TryTranslateText(result.externalLink, database);
			
					
				}
				
	
		return result;
	}
	
	private String getPreviewImageUrlForArticle(String name, SQLiteDatabase database)
	{
		String result = "R.drawable.no_picture";
		
		ArrayList<String> albumNameArr = innerGetAlbumNameArrInArticle(name, database);
		
		if (albumNameArr.size() > 0)
		{
			AlbumFullData album = MainActivity.getInstance().albumDataSource.InnerGetAlbumFullData(albumNameArr.get(0), database);
			
			if (album.photoRecordArr.size() > 0)
			{
				result = album.photoRecordArr.get(0).imageUrl;
			}
			
		}
		
		if (result.equals("R.drawable.no_picture"))
		{
			ArrayList<String> channelNameArr = innerGetChannelNameArrInArticle(name, database);
			
			if (channelNameArr.size() > 0)
			{
				ChannelFullData channelFullData = MainActivity.getInstance().channelDataSource.InnerGetChannelFullData(channelNameArr.get(0), database);
											
				if (channelFullData.videoRecordArr.size() > 0)
				{
					result = channelFullData.videoRecordArr.get(0).previewImageUrl;
				}
			}
		}
		
		return result;
	}
	
	private boolean innerIsArticleAlreadyExist(String name, SQLiteDatabase database)
	{
		boolean result = false;
		
		Cursor cursor = database.query(BashgidSqliteHelper.TABLE_ARTICLE, new String[] { BashgidSqliteHelper.COLUMN_NAME },
				BashgidSqliteHelper.COLUMN_NAME + "=?", new String[] { name }, null, null, null, null);

		if (cursor != null)
		{
			if (cursor.getCount() > 0)
			{
				result = true;
			}
			
			cursor.close();
			cursor = null;
		} 
		
		return result;

	}
	
	
	
	private boolean innerAlbumArticleRelationAlreadyExist(String albumName, String articleName, SQLiteDatabase database)
	{
		boolean result = false;
		
		Cursor cursor = database.query(BashgidSqliteHelper.TABLE_ALBUM_ARTICLE_RELATION, new String[] { BashgidSqliteHelper.COLUMN_ALBUM_NAME, BashgidSqliteHelper.COLUMN_ARTICLE_NAME },
				BashgidSqliteHelper.COLUMN_ALBUM_NAME + "=?" + " AND " + BashgidSqliteHelper.COLUMN_ARTICLE_NAME + "=?", new String[] { albumName, articleName }, null, null, null, null);

		if (cursor != null)
		{
			if (cursor.getCount() > 0)
			{
				result = true;
			}
			cursor.close();
			cursor = null;
		} 
		
		return result;

	}
	
	private boolean innerChannelArticleRelationAlreadyExist(String channelName, String articleName, SQLiteDatabase database)
	{
		boolean result = false;
		
		Cursor cursor = database.query(BashgidSqliteHelper.TABLE_CHANNEL_ARTICLE_RELATION, new String[] { BashgidSqliteHelper.COLUMN_CHANNEL_NAME, BashgidSqliteHelper.COLUMN_ARTICLE_NAME },
				BashgidSqliteHelper.COLUMN_CHANNEL_NAME + "=?" + " AND " + BashgidSqliteHelper.COLUMN_ARTICLE_NAME + "=?", new String[] { channelName, articleName }, null, null, null, null);

		if (cursor != null)
		{
			if (cursor.getCount() > 0)
			{
				result = true;
			}
			
			cursor.close();
			cursor = null;
		} 
		
		return result;

	}
	
	private ArticleRecordData innerGetArticleByName(String name, SQLiteDatabase database)
	{
		
		ArticleRecordData result = null;
		
		Cursor cursor = database.query(BashgidSqliteHelper.TABLE_ARTICLE, new String[] { 
				BashgidSqliteHelper.COLUMN_NAME,
				BashgidSqliteHelper.COLUMN_TYPE,
				BashgidSqliteHelper.COLUMN_TITLE,
				BashgidSqliteHelper.COLUMN_CONTENT,
				BashgidSqliteHelper.COLUMN_GEOLAT,
				BashgidSqliteHelper.COLUMN_GEOLON,
				BashgidSqliteHelper.COLUMN_ADDRESS,
				BashgidSqliteHelper.COLUMN_PHONE,
				BashgidSqliteHelper.COLUMN_EXTERNAL_LINK,
				BashgidSqliteHelper.COLUMN_EXTERNAL_LINK_TEXT,
				BashgidSqliteHelper.COLUMN_DATE_TIME,
				BashgidSqliteHelper.COLUMN_HIDDEN
				},
				BashgidSqliteHelper.COLUMN_NAME + "=?", new String[] { name }, null, null, null, null);

		if (cursor != null)
		{
			if (cursor.moveToFirst())
			{
	
				Date d = new Date();
	
				try
				{
					d = ArticleManager.iso8601Format.parse(cursor.getString(10));
				}
				catch(ParseException e)
				{
					Log.e("aaa", "aaa!!!!!");
				}
				
				result = new ArticleRecordData(
						cursor.getString(0),
						cursor.getInt(1),
						cursor.getString(2),
						cursor.getString(3),
						cursor.getDouble(4),
						cursor.getDouble(5),
						cursor.getString(6),
						cursor.getString(7),
						cursor.getString(8),
						cursor.getString(9),
						d,
						cursor.getInt(11)
						);						
			}
			
			cursor.close();
			cursor = null;
		} 
		
		return result;

	}
	
	private ArrayList<ArticleRecordData> innerGetArticlesByQuery(String query, SQLiteDatabase database)
	{
		
		ArrayList<ArticleRecordData> result = new ArrayList<ArticleRecordData>();
		
		Cursor cursor = database.query(BashgidSqliteHelper.TABLE_ARTICLE, new String[] { 
				BashgidSqliteHelper.COLUMN_NAME,
				BashgidSqliteHelper.COLUMN_TYPE,
				BashgidSqliteHelper.COLUMN_TITLE,
				BashgidSqliteHelper.COLUMN_CONTENT,
				BashgidSqliteHelper.COLUMN_GEOLAT,
				BashgidSqliteHelper.COLUMN_GEOLON,
				BashgidSqliteHelper.COLUMN_ADDRESS,
				BashgidSqliteHelper.COLUMN_PHONE,
				BashgidSqliteHelper.COLUMN_EXTERNAL_LINK,
				BashgidSqliteHelper.COLUMN_EXTERNAL_LINK_TEXT,
				BashgidSqliteHelper.COLUMN_DATE_TIME,
				BashgidSqliteHelper.COLUMN_HIDDEN
				},
				BashgidSqliteHelper.COLUMN_TITLE + " LIKE ?", new String[] { "%" + query + "%" }, null, null, null, null);

		if (cursor != null)
		{
			if (cursor.moveToFirst())
			{
				
				do
				{
	
				Date d = new Date();
	
				try
				{
					d = ArticleManager.iso8601Format.parse(cursor.getString(10));
				}
				catch(ParseException e)
				{
					Log.e("aaa", "aaa!!!!!");
				}
				
				result.add(new ArticleRecordData(
						cursor.getString(0),
						cursor.getInt(1),
						cursor.getString(2),
						cursor.getString(3),
						cursor.getDouble(4),
						cursor.getDouble(5),
						cursor.getString(6),
						cursor.getString(7),
						cursor.getString(8),
						cursor.getString(9),
						d,
						cursor.getInt(11)
						));	
				
				}
				while (cursor.moveToNext());
			}
			
			cursor.close();
			cursor = null;
		} 
		
		return result;

	}
	
	
	private ArrayList<String> InnerSearchArticleByTitleOrText(String query, SQLiteDatabase database)
	{
		
		ArrayList<String> result = new ArrayList<String>();
		
		Cursor cursor = database.query(BashgidSqliteHelper.TABLE_ARTICLE, new String[] { 
				BashgidSqliteHelper.COLUMN_NAME
				},
				BashgidSqliteHelper.COLUMN_TITLE + " = ? OR " + BashgidSqliteHelper.COLUMN_CONTENT + " = ?", new String[] { query, query }, null, null, null, null);

		if (cursor != null)
		{
			if (cursor.moveToFirst())
			{
				
				do
				{
				
				result.add(cursor.getString(0));	
				
				}
				while (cursor.moveToNext());
			}
			
			cursor.close();
			cursor = null;
		} 
		
		return result;

	}
	
	public ArrayList<String> innerGetAlbumNameArrInArticle(String name, SQLiteDatabase database)
	{
		ArrayList<String> result = new ArrayList<String>();
		
		Cursor cursor = database.query(BashgidSqliteHelper.TABLE_ALBUM_ARTICLE_RELATION, new String[] { BashgidSqliteHelper.COLUMN_ALBUM_NAME },
				BashgidSqliteHelper.COLUMN_ARTICLE_NAME + "=?", new String[] { name }, null, null, null, null);

		if (cursor != null)
		{
			if (cursor.moveToFirst())
			{
				do
				{
					result.add(cursor.getString(0));
				}
				while (cursor.moveToNext());
							
			}
			
			cursor.close();
			cursor = null;
		} 
		
		return result;

	}
	
	private ArrayList<String> innerGetChannelNameArrInArticle(String name, SQLiteDatabase database)
	{
		ArrayList<String> result = new ArrayList<String>();
		
		Cursor cursor = database.query(BashgidSqliteHelper.TABLE_CHANNEL_ARTICLE_RELATION, new String[] { BashgidSqliteHelper.COLUMN_CHANNEL_NAME },
				BashgidSqliteHelper.COLUMN_ARTICLE_NAME + "=?", new String[] { name }, null, null, null, null);

		if (cursor != null)
		{
			if (cursor.moveToFirst())
			{
				do
				{
					result.add(cursor.getString(0));
				}
				while (cursor.moveToNext());
							
			}
			
			cursor.close();
			cursor = null;
		} 
		
		return result;

	}
	
	

}
