package fishrungames.bashgid;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import fishrungames.bashgid.core.DatabaseDownloadTask;
import fishrungames.bashgid.core.NewsDownloadTask;
import fishrungames.bashgid.core.AlbumManager.AlbumFullData;
import fishrungames.bashgid.core.AlbumManager.AlbumShortData;
import fishrungames.bashgid.core.ArticleManager.ArticleFullData;
import fishrungames.bashgid.core.ArticleManager.ArticleShortData;
import fishrungames.bashgid.core.ChannelManager.ChannelFullData;
import fishrungames.bashgid.core.JournalManager.JournalRecordData;
import fishrungames.bashgid.core.JournalManager.JournalSemiFullData;
import fishrungames.bashgid.core.VideoManager.VideoRecordData;
import fishrungames.bashgid.core.db.AlbumDataSource;
import fishrungames.bashgid.core.db.ArticleDataSource;
import fishrungames.bashgid.core.db.BashgidSqliteHelper;
import fishrungames.bashgid.core.db.ChannelDataSource;
import fishrungames.bashgid.core.db.JournalDataSource;
import fishrungames.bashgid.core.db.PhotoDataSource;
import fishrungames.bashgid.core.db.TranslationDataSource;
import fishrungames.bashgid.core.db.VideoDataSource;
import fishrungames.networkutils.ContextHolder;
import fishrungames.networkutils.ImageDownloadTask;
import fishrungames.networkutils.ImageManager;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.format.DateUtils;

public class BashgidApplication extends android.app.Application {

	public static final String PREFS_MAIN = "PREFS_MAIN";
	
	public static final int NEWS_DOWNLOADER_STATE_UPDATE = 10;
	public static final int NEWS_DOWNLOADER_STATE_FINISHED = 11;

	public static final int DATABASE_DOWNLOADER_STATE_UPDATE = 12;
	public static final int DATABASE_DOWNLOADER_STATE_FINISHED = 13;

	public static final int DATABASE_GET_ALBUM_STATE_UPDATE = 14;
	public static final int DATABASE_GET_ALBUM_STATE_FINISHED = 15;

	public static final int DATABASE_GET_ALBUM_LIST_STATE_UPDATE = 16;
	public static final int DATABASE_GET_ALBUM_LIST_STATE_FINISHED = 17;

	public static final int DATABASE_GET_ARTICLE_STATE_UPDATE = 18;
	public static final int DATABASE_GET_ARTICLE_STATE_FINISHED = 19;

	public static final int DATABASE_GET_JOURNAL_STATE_UPDATE = 20;
	public static final int DATABASE_GET_JOURNAL_STATE_FINISHED = 21;

	public static final int DATABASE_GET_CHANNEL_STATE_UPDATE = 22;
	public static final int DATABASE_GET_CHANNEL_STATE_FINISHED = 23;

	public static final int DATABASE_GET_VIDEO_STATE_UPDATE = 24;
	public static final int DATABASE_GET_VIDEO_STATE_FINISHED = 25;

	public static final int DATABASE_GET_JOURNAL_LIST_STATE_UPDATE = 26;
	public static final int DATABASE_GET_JOURNAL_LIST_STATE_FINISHED = 27;

	public static final int DATABASE_SEARCH_ARTICLE_STATE_UPDATE = 28;
	public static final int DATABASE_SEARCH_ARTICLE_STATE_FINISHED = 29;

	public static final int DATABASE_GET_GEO_JOURNAL_LIST_STATE_UPDATE = 30;
	public static final int DATABASE_GET_GEO_JOURNAL_LIST_STATE_FINISHED = 31;

	
    private static BashgidApplication instance = null;

    public static final SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
    
    private static ImageDownloadTask imageDownloadTask = null;

	private static ArrayList<String> queuedImgUrlArr = new ArrayList<String>();
	private static ArrayList<String> queuedImgHashArr = new ArrayList<String>();
	
	
	public static Handler mainHandler;
	
	public BashgidSqliteHelper dbHelper = null;

	
	public static PhotoDataSource photoDataSource = null;
	public static AlbumDataSource albumDataSource = null;
	public static ArticleDataSource articleDataSource = null;

	public static VideoDataSource videoDataSource = null;
	public static ChannelDataSource channelDataSource = null;

	public static JournalDataSource journalDataSource = null;

	public static TranslationDataSource translationDataSource = null;
	
	public static NewsDownloadTask newsDownloadTask = null;
	public static DatabaseDownloadTask databaseDownloadTask = null;
	

    
    public BashgidApplication() {
    	instance = this;
    	
    	ImageManager.getInstance().PredefinedImageId.put("R.drawable.no_picture", R.drawable.no_picture);
	
		ImageManager.PreferredEmptyPicture = "R.drawable.no_picture";
		
		ImageManager.getInstance().alwaysUpdateImagesWithoutHash = false;
		
		ContextHolder.setContext(instance);
		
		
		
		
		dbHelper = new BashgidSqliteHelper(this);

		photoDataSource = new PhotoDataSource(this, dbHelper);

		albumDataSource = new AlbumDataSource(this, dbHelper);

		articleDataSource = new ArticleDataSource(this, dbHelper);

		videoDataSource = new VideoDataSource(this, dbHelper);

		channelDataSource = new ChannelDataSource(this, dbHelper);

		journalDataSource = new JournalDataSource(this, dbHelper);

		translationDataSource = new TranslationDataSource(this, dbHelper);
		
		
		
		
		

		mainHandler = new Handler(Looper.getMainLooper())
		{
			@Override
			public void handleMessage(Message inputMessage)
			{

				switch (inputMessage.what)
				{
				
				case ImageDownloadTask.IMAGE_DOWNLOADER_STATE_UPDATE:
					MainActivity.getInstance().UpdateOnImageDownloaded();
					break;
				case ImageDownloadTask.IMAGE_DOWNLOADER_STATE_FINISHED:
					MainActivity.getInstance().UpdateOnImageDownloaded();
					
					OnImageDownloaderStateFinished();
					
					break;
				case NEWS_DOWNLOADER_STATE_UPDATE:
					SetNewsDownloadProgress((Integer)inputMessage.obj);
					MainActivity.getInstance().UpdateOnNewsDownloaded((Integer)inputMessage.obj);
					break;
				case NEWS_DOWNLOADER_STATE_FINISHED:
					MainActivity.getInstance().UpdateOnNewsDownloaded((Integer)inputMessage.obj);
					newsDownloadTask = null;
					break;
				case DATABASE_DOWNLOADER_STATE_UPDATE:
					MainActivity.getInstance().UpdateOnDatabaseDownloaded((Integer)inputMessage.obj);
					break;
				case DATABASE_DOWNLOADER_STATE_FINISHED:
					MainActivity.getInstance().UpdateOnDatabaseDownloaded((Integer)inputMessage.obj);
					databaseDownloadTask = null;
					break;
				
				case DATABASE_GET_JOURNAL_STATE_UPDATE:
				case DATABASE_GET_JOURNAL_STATE_FINISHED:
					final JournalSemiFullData journal = (JournalSemiFullData) inputMessage.obj;
					MainActivity.getInstance().UpdateOnJournalLoaded(journal);
					break;
				case DATABASE_GET_JOURNAL_LIST_STATE_UPDATE:
				case DATABASE_GET_JOURNAL_LIST_STATE_FINISHED:
					MainActivity.getInstance().UpdateOnJournalListLoaded((ArrayList<JournalSemiFullData>) inputMessage.obj);
					break;
					
				case DATABASE_GET_ALBUM_STATE_UPDATE:
				case DATABASE_GET_ALBUM_STATE_FINISHED:
					MainActivity.getInstance().UpdateOnAlbumLoaded((AlbumFullData) inputMessage.obj);
					break;
				case DATABASE_GET_ALBUM_LIST_STATE_UPDATE:
				case DATABASE_GET_ALBUM_LIST_STATE_FINISHED:

					ArrayList<AlbumShortData> albumShortList = (ArrayList<AlbumShortData>) inputMessage.obj;
					MainActivity.getInstance().UpdateOnAlbumListLoaded(albumShortList);
					break;
				case DATABASE_GET_ARTICLE_STATE_UPDATE:
				case DATABASE_GET_ARTICLE_STATE_FINISHED:
					MainActivity.getInstance().UpdateOnArticleLoaded((ArticleFullData) inputMessage.obj);
					break;
					
				case DATABASE_GET_CHANNEL_STATE_UPDATE:
				case DATABASE_GET_CHANNEL_STATE_FINISHED:
					MainActivity.getInstance().UpdateOnChannelLoaded((ChannelFullData) inputMessage.obj);
					break;

				case DATABASE_GET_VIDEO_STATE_UPDATE:
				case DATABASE_GET_VIDEO_STATE_FINISHED:
					MainActivity.getInstance().UpdateOnVideoLoaded((VideoRecordData) inputMessage.obj);
					break;



				case DATABASE_SEARCH_ARTICLE_STATE_UPDATE:
				case DATABASE_SEARCH_ARTICLE_STATE_FINISHED:
					MainActivity.getInstance().UpdateOnArticleSearchPerformed((ArrayList<ArticleShortData>) inputMessage.obj);
					break;

				case DATABASE_GET_GEO_JOURNAL_LIST_STATE_UPDATE:
				case DATABASE_GET_GEO_JOURNAL_LIST_STATE_FINISHED:
					MainActivity.getInstance().UpdateOnGeoJournalListLoaded((ArrayList<JournalRecordData>) inputMessage.obj);
					break;
				default:
					super.handleMessage(inputMessage);
				}
			}

		};
		
    }

    public static Context getContext() {
    	return instance;
    }
    
   
    
    
    public static void OnImageDownloaderStateFinished()
    {
    	imageDownloadTask = null;
		DownloadRestImageArr();
    }
    
    
    public static void DownloadImageArr(String[] imageUrlArr, String[] imageHashArr)
	{
		
		synchronized(queuedImgUrlArr)
		{
			
			for (int i = 0; i < imageUrlArr.length; i++)
			{
				queuedImgUrlArr.add(imageUrlArr[i]);
				
				if (imageHashArr[i] == null)
				{
					queuedImgHashArr.add("");
				}
				else
				{
					queuedImgHashArr.add(imageHashArr[i]);
				}
			}

		
		}
		
		if (imageDownloadTask == null)
		{
			DownloadRestImageArr();
		}
		
		
	}
	
	public static void DownloadRestImageArr()
	{
		synchronized(queuedImgUrlArr)
		{
			if (queuedImgUrlArr.size() > 0)
			{
			imageDownloadTask = new ImageDownloadTask();

			imageDownloadTask.mHandler = mainHandler;
			
			Bundle innerQuery = new Bundle();
			
			String[] imageUrlArr = queuedImgUrlArr.toArray(new String[queuedImgUrlArr.size()]);
			String[] imageHashArr = queuedImgHashArr.toArray(new String[queuedImgHashArr.size()]);
			
			innerQuery.putStringArray("imageUrlArr", imageUrlArr);
			innerQuery.putStringArray("imageHashArr", imageHashArr);
			
			queuedImgUrlArr.clear();
			queuedImgHashArr.clear();

			imageDownloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, innerQuery);
			
			}
		}
	}

	public static void DownloadImage(String imageUrl, String imageHash)
	{

		DownloadImageArr(new String[] { imageUrl }, new String[] { imageHash });
	}
	
	
	
	
	
	
	 public static void CancelDownloadDatabaseTask()
		{
			if (databaseDownloadTask != null)
			{
				databaseDownloadTask.cancel(false);
				databaseDownloadTask = null;
			}
			
			MainActivity.getInstance().UpdateOnDatabaseDownloaded(0);
		}

		public static void DownloadDatabase()
		{

			if (databaseDownloadTask != null)
			{
				return;
			}
			
			databaseDownloadTask = new DatabaseDownloadTask();

			databaseDownloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}
		
		
		
		public static void CancelDownloadNewsTask()
		{
			if (newsDownloadTask != null)
			{
				newsDownloadTask.cancel(false);
				newsDownloadTask = null;
			}
			
			MainActivity.getInstance().UpdateOnNewsDownloaded(0);
		}
		
		public static void StartDownloadNewsTask()
		{

			if (newsDownloadTask != null)
			{
				return;
			}
			
			newsDownloadTask = new NewsDownloadTask();

			newsDownloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}
		
		
	
    
    public static void SetLastAlbumName(String lastAlbumName)
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);

		SharedPreferences.Editor editor = settings.edit();
		editor.putString("lastAlbumName", lastAlbumName);
		editor.commit();
	}

	public static String GetLastAlbumName()
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);
		return settings.getString("lastAlbumName", "");
	}
	
	public static void SetLastChannelName(String lastChannelName)
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);

		SharedPreferences.Editor editor = settings.edit();
		editor.putString("lastChannelName", lastChannelName);
		editor.commit();
	}

	public static String GetLastChannelName()
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);
		return settings.getString("lastChannelName", "");
	}

	public static void SetLastArticleName(String lastArticleName)
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);

		SharedPreferences.Editor editor = settings.edit();
		editor.putString("lastArticleName", lastArticleName);
		editor.commit();
	}

	public static String GetLastArticleName()
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);
		return settings.getString("lastArticleName", "");
	}
	
	
	
	public static void SetLastJournalName(String lastJournalName)
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);

		SharedPreferences.Editor editor = settings.edit();
		editor.putString("lastJournalName", lastJournalName);
		editor.commit();
	}

	
	public static String GetLastJournalName()
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);
		return settings.getString("lastJournalName", "");
	}

	
	public static void SetLastJournalTitle(String lastJournalTitle)
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);

		SharedPreferences.Editor editor = settings.edit();
		editor.putString("lastJournalTitle", lastJournalTitle);
		editor.commit();
	}
	
	public static String GetLastJournalTitle()
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);
		return settings.getString("lastJournalTitle", "");
	}
	
	public static void SetLastSearchQuery(String searchQuery)
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);

		SharedPreferences.Editor editor = settings.edit();
		editor.putString("searchQuery", searchQuery);
		editor.commit();
	}

	public static String GetLastSearchQuery()
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);
		return settings.getString("searchQuery", "");
	}

	public static void SetLastMapFilterName(String lastMapFilterName)
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);

		SharedPreferences.Editor editor = settings.edit();
		editor.putString("lastMapFilterName", lastMapFilterName);
		editor.commit();
	}

	public static String GetLastMapFilterName()
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);
		return settings.getString("lastMapFilterName", "");
	}
	
	public static void SetNewsDownloadProgress(int newsDownloadProgress)
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);

		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("newsDownloadProgress", newsDownloadProgress);
		editor.commit();
	}

	public static int GetNewsDownloadProgress()
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);
		return settings.getInt("newsDownloadProgress", 0);
	}
	
	public static void SetDatabaseDownloadProgress(int databaseDownloadProgress)
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);

		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("databaseDownloadProgress", databaseDownloadProgress);
		editor.commit();
	}

	public static int GetDatabaseDownloadProgress()
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);
		return settings.getInt("databaseDownloadProgress", 0);
	}
	
	public static void SetLastLanguage(int lastLanguage)  //0 russian, 1 english, 2 chinese
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);

		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("lastLanguage", lastLanguage);
		editor.commit();
	}

	public static int GetLastLanguage()
	{
		SharedPreferences settings = instance.getSharedPreferences(PREFS_MAIN, 0);
		return settings.getInt("lastLanguage", 0);
	}
	
	public static String DateFormattedForLocale(Date date)
	{
		return DateUtils.formatDateTime(instance, date.getTime(), DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE  | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_YEAR);
		
	}

}