package fishrungames.bashgid.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.database.DatabaseUtils;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import fishrungames.bashgid.BashgidApplication;
import fishrungames.bashgid.MainActivity;
import fishrungames.bashgid.core.AlbumManager.AlbumRecordData;
import fishrungames.bashgid.core.ArticleManager.ArticleRecordData;
import fishrungames.bashgid.core.ChannelManager.ChannelRecordData;
import fishrungames.bashgid.core.JournalManager.JournalRecordData;
import fishrungames.bashgid.core.PhotoManager.PhotoRecordData;
import fishrungames.bashgid.core.TranslationManager.TranslationRecordData;
import fishrungames.bashgid.core.VideoManager.VideoRecordData;
import fishrungames.networkutils.SimpleAsyncTask;

public class DatabaseDownloadTask extends SimpleAsyncTask
{

	protected Long doInBackground(Bundle... queryArr)
	{
		
		
		
		PublishProgress(0.1f);
		
		if (isCancelled())
		{
			return (long)0;
		}
		
		ParseJsonTranslation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=translation/json"));
		PublishProgress(0.2f);
		
		if (isCancelled())
		{
			return (long)0;
		}

		ParseJsonPhoto(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=photo/json"));
		PublishProgress(0.25f);
		
		if (isCancelled())
		{
			return (long)0;
		}

		ParseJsonAlbum(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=album/json"));
		PublishProgress(0.3f);
		
		if (isCancelled())
		{
			return (long)0;
		}

		ParseJsonPhotoAlbumRelation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=photoAlbumRelation/json"));
		PublishProgress(0.35f);
		
		if (isCancelled())
		{
			return (long)0;
		}

		ParseJsonVideo(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=video/json"));
		PublishProgress(0.4f);
		
		if (isCancelled())
		{
			return (long)0;
		}

		ParseJsonChannel(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=channel/json"));
		PublishProgress(0.5f);
		
		if (isCancelled())
		{
			return (long)0;
		}

		ParseJsonVideoChannelRelation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=videoChannelRelation/json"));
		PublishProgress(0.6f);

		if (isCancelled())
		{
			return (long)0;
		}
		
		ParseJsonArticle(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=article/json"));
		PublishProgress(0.65f);

		if (isCancelled())
		{
			return (long)0;
		}
		
		ParseJsonAlbumArticleRelation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=albumArticleRelation/json"));
		PublishProgress(0.85f);
		
		if (isCancelled())
		{
			return (long)0;
		}

		ParseJsonChannelArticleRelation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=channelArticleRelation/json"));
		PublishProgress(0.9f);
		
		if (isCancelled())
		{
			return (long)0;
		}

		ParseJsonJournal(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=journal/json"));
		PublishProgress(0.75f);
	
		if (isCancelled())
		{
			return (long)0;
		}

		ParseJsonArticleJournalRelation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=articleJournalRelation/json"));
		PublishProgress(0.95f);

		return (long) 0;
	}
	
	

	protected void onProgressUpdate(Integer... progress)
	{
		Message completeMessage = BashgidApplication.mainHandler.obtainMessage(BashgidApplication.DATABASE_DOWNLOADER_STATE_UPDATE, progress[0]);

		completeMessage.sendToTarget();

	}

	protected void onPostExecute(Long result)
	{
		Message completeMessage = BashgidApplication.mainHandler.obtainMessage(BashgidApplication.DATABASE_DOWNLOADER_STATE_FINISHED, 100);

		completeMessage.sendToTarget();
	}
	
	public void ReloadDatabaseContent()
	{
		//journalList = MainActivity.getInstance().journalDataSource.GetJournalListMain(3);
	}

	private String getJsonFromUrl(String url_select)
	{

		ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

		InputStream inputStream = null;

		try
		{
			// Set up HTTP post

			// HttpClient is more then less deprecated. Need to change to
			// URLConnection
			HttpClient httpClient = new DefaultHttpClient();

			HttpPost httpPost = new HttpPost(url_select);
			httpPost.setEntity(new UrlEncodedFormEntity(param));
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();

			// Read content & Log
			inputStream = httpEntity.getContent();
		} catch (UnsupportedEncodingException e1)
		{
			Log.e("UnsupportedEncodingException", e1.toString());
			e1.printStackTrace();
		} catch (ClientProtocolException e2)
		{
			Log.e("ClientProtocolException", e2.toString());
			e2.printStackTrace();
		} catch (IllegalStateException e3)
		{
			Log.e("IllegalStateException", e3.toString());
			e3.printStackTrace();
		} catch (IOException e4)
		{
			Log.e("IOException", e4.toString());
			e4.printStackTrace();
		}
		// Convert response to string using String Builder
		try
		{
			BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
			StringBuilder sBuilder = new StringBuilder();

			String line = null;
			while ((line = bReader.readLine()) != null)
			{
				sBuilder.append(line + "\n");
			}

			inputStream.close();
			String result = sBuilder.toString();

			return result;

		} catch (Exception e)
		{
			Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
		}

		return "";

	}

	private void ParseJsonPhoto(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				JSONObject jObject = jArray.getJSONObject(i);

				String title = DatabaseDownloadTask.sqlEscapeString(jObject.getString("title"));
				String description = DatabaseDownloadTask.sqlEscapeString(jObject.getString("description"));
				String imageUrl = DatabaseDownloadTask.sqlEscapeString(jObject.getString("imageUrl"));
				String imageHash = DatabaseDownloadTask.sqlEscapeString(jObject.getString("imageHash"));
				double geoLat = jObject.getDouble("geoLat");
				double geoLon = jObject.getDouble("geoLon");

				BashgidApplication.photoDataSource.AddOrReplacePhoto(new PhotoRecordData(title, description, imageUrl, imageHash, geoLat, geoLon));

				BashgidApplication.DownloadImage(imageUrl, imageHash);

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}

	private void ParseJsonAlbum(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				JSONObject jObject = jArray.getJSONObject(i);

				String name = DatabaseDownloadTask.sqlEscapeString(jObject.getString("name"));
				String title = DatabaseDownloadTask.sqlEscapeString(jObject.getString("title"));
				String description = DatabaseDownloadTask.sqlEscapeString(jObject.getString("description"));
				int hidden = jObject.getInt("hidden");

				BashgidApplication.albumDataSource.CreateNewAlbum(new AlbumRecordData(name, title, description, hidden));

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}

	private void ParseJsonPhotoAlbumRelation(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				JSONObject jObject = jArray.getJSONObject(i);

				String imageUrl = DatabaseDownloadTask.sqlEscapeString(jObject.getString("imageUrl"));
				String name = DatabaseDownloadTask.sqlEscapeString(jObject.getString("name"));

				BashgidApplication.albumDataSource.AddPhotoToAlbum(imageUrl, name);

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}

	private void ParseJsonVideo(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				JSONObject jObject = jArray.getJSONObject(i);

				int type = jObject.getInt("type");
				String videoUrl = DatabaseDownloadTask.sqlEscapeString(jObject.getString("videoUrl"));

				String title = DatabaseDownloadTask.sqlEscapeString(jObject.getString("title"));
				String description = DatabaseDownloadTask.sqlEscapeString(jObject.getString("description"));
				String previewImageUrl = DatabaseDownloadTask.sqlEscapeString(jObject.getString("previewImageUrl"));
				String previewImageHash = DatabaseDownloadTask.sqlEscapeString(jObject.getString("previewImageHash"));

				BashgidApplication.videoDataSource.AddOrReplaceVideo(new VideoRecordData(type, videoUrl, title, description, previewImageUrl,
						previewImageHash));

				BashgidApplication.DownloadImage(previewImageUrl, previewImageHash);

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}

	private void ParseJsonChannel(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				JSONObject jObject = jArray.getJSONObject(i);

				String name = DatabaseDownloadTask.sqlEscapeString(jObject.getString("name"));
				String title = DatabaseDownloadTask.sqlEscapeString(jObject.getString("title"));
				String description = DatabaseDownloadTask.sqlEscapeString(jObject.getString("description"));
				int hidden = jObject.getInt("hidden");

				BashgidApplication.channelDataSource.CreateNewChannel(new ChannelRecordData(name, title, description, hidden));

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}

	private void ParseJsonVideoChannelRelation(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				JSONObject jObject = jArray.getJSONObject(i);

				String videoUrl = DatabaseDownloadTask.sqlEscapeString(jObject.getString("videoUrl"));
				String name = DatabaseDownloadTask.sqlEscapeString(jObject.getString("name"));

				BashgidApplication.channelDataSource.AddVideoToChannel(videoUrl, name);

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}

	private void ParseJsonArticle(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				try
				{
					JSONObject jObject = jArray.getJSONObject(i);

					String name = DatabaseDownloadTask.sqlEscapeString(jObject.getString("name"));
					int type = jObject.getInt("type");
					String title = DatabaseDownloadTask.sqlEscapeString(jObject.getString("title"));
					String content = DatabaseDownloadTask.sqlEscapeString(jObject.getString("content"));
					double geoLat = jObject.getDouble("geoLat");
					double geoLon = jObject.getDouble("geoLon");
					String address = DatabaseDownloadTask.sqlEscapeString(jObject.getString("address"));
					String phone = DatabaseDownloadTask.sqlEscapeString(jObject.getString("phone"));
					String externalLink = DatabaseDownloadTask.sqlEscapeString(jObject.getString("externalLink"));
					String externalLinkText = DatabaseDownloadTask.sqlEscapeString(jObject.getString("externalLinkText"));
					Date dateTime = ArticleManager.iso8601Format.parse(jObject.getString("dateTime"));
					int hidden = jObject.getInt("hidden");

					BashgidApplication.articleDataSource.CreateNewArticle(new ArticleRecordData(name, type, title, content, geoLat, geoLon, address,
							phone, externalLink, externalLinkText, dateTime, hidden));

				} catch (ParseException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}

	private void ParseJsonJournal(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				JSONObject jObject = jArray.getJSONObject(i);

				String name = DatabaseDownloadTask.sqlEscapeString(jObject.getString("name"));
				String title = DatabaseDownloadTask.sqlEscapeString(jObject.getString("title"));
				String description = DatabaseDownloadTask.sqlEscapeString(jObject.getString("description"));
				int hidden = jObject.getInt("hidden");
				int geoCategory = jObject.getInt("geoCategory");
				int main = jObject.getInt("main");

				BashgidApplication.journalDataSource.CreateNewJournal(new JournalRecordData(name, title, description, hidden, geoCategory, main));

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}

	private void ParseJsonAlbumArticleRelation(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				JSONObject jObject = jArray.getJSONObject(i);

				String albumName = DatabaseDownloadTask.sqlEscapeString(jObject.getString("albumName"));
				String articleName = DatabaseDownloadTask.sqlEscapeString(jObject.getString("articleName"));

				BashgidApplication.articleDataSource.AddAlbumToArticle(albumName, articleName);

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}

	private void ParseJsonChannelArticleRelation(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				JSONObject jObject = jArray.getJSONObject(i);

				String channelName = DatabaseDownloadTask.sqlEscapeString(jObject.getString("channelName"));
				String articleName = DatabaseDownloadTask.sqlEscapeString(jObject.getString("articleName"));

				BashgidApplication.articleDataSource.AddChannelToArticle(channelName, articleName);

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}

	private void ParseJsonArticleJournalRelation(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				JSONObject jObject = jArray.getJSONObject(i);

				String articleName = DatabaseDownloadTask.sqlEscapeString(jObject.getString("articleName"));
				String journalName = DatabaseDownloadTask.sqlEscapeString(jObject.getString("journalName"));

				BashgidApplication.journalDataSource.AddArticleToJournal(articleName, journalName);

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}

	private void ParseJsonTranslation(String jsonCode)
	{
		try
		{
			JSONArray jArray = new JSONArray(jsonCode);

			for (int i = 0; i < jArray.length(); i++)
			{

				JSONObject jObject = jArray.getJSONObject(i);

				String name = DatabaseDownloadTask.sqlEscapeString(jObject.getString("name"));
				String textEn = DatabaseDownloadTask.sqlEscapeString(jObject.getString("textEn"));
				String textRu = DatabaseDownloadTask.sqlEscapeString(jObject.getString("textRu"));
				String textZh = DatabaseDownloadTask.sqlEscapeString(jObject.getString("textZh"));
				String textEnUp = DatabaseDownloadTask.sqlEscapeString(jObject.getString("textEnUp"));
				String textRuUp = DatabaseDownloadTask.sqlEscapeString(jObject.getString("textRuUp"));
				String textZhUp = DatabaseDownloadTask.sqlEscapeString(jObject.getString("textZhUp"));

				BashgidApplication.translationDataSource.CreateNewTranslation(new TranslationRecordData(name, textEn, textRu, textZh, textEnUp,
						textRuUp, textZhUp));

			} // End Loop

		} catch (JSONException e)
		{
			Log.e("JSONException", "Error: " + e.toString());
		}
	}
	
	
	public static String sqlEscapeString_withquotes(String s)
	{
		String result = DatabaseUtils.sqlEscapeString(s);
		
		result = result.substring(1, result.length()-1);
		
		return result;
	}
	
	public static String sqlEscapeString(String s)
	{
		/*
		String result = s;
				
		result = DatabaseUtils.sqlEscapeString(result);
		
		result = result.substring(1, result.length()-1);
		
		return result;*/
		return s;
	}

}