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.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
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;

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

	public Handler mHandler;

	protected Long doInBackground(Bundle... queryArr)
	{

		ParseJsonPhoto(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=photo/json"));
		ParseJsonAlbum(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=album/json"));
		ParseJsonPhotoAlbumRelation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=photoAlbumRelation/json"));

		ParseJsonVideo(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=video/json"));
		ParseJsonChannel(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=channel/json"));
		ParseJsonVideoChannelRelation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=videoChannelRelation/json"));

		ParseJsonArticle(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=article/json"));
		ParseJsonJournal(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=journal/json"));
		ParseJsonAlbumArticleRelation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=albumArticleRelation/json"));
		ParseJsonChannelArticleRelation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=channelArticleRelation/json"));
		ParseJsonArticleJournalRelation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=articleJournalRelation/json"));
		ParseJsonTranslation(getJsonFromUrl("http://bashgid.hallyu.ru/index.php?r=translation/json"));

		return (long) 0;
	}

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

		completeMessage.sendToTarget();

	}

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

		completeMessage.sendToTarget();
	}

	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 = jObject.getString("title");
				String description = jObject.getString("description");
				String imageUrl = jObject.getString("imageUrl");
				String imageHash = jObject.getString("imageHash");
				double geoLat = jObject.getDouble("geoLat");
				double geoLon = jObject.getDouble("geoLon");

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

				MainActivity.getInstance().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 = jObject.getString("name");
				String title = jObject.getString("title");
				String description = jObject.getString("description");
				int hidden = jObject.getInt("hidden");

				MainActivity.getInstance().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 = jObject.getString("imageUrl");
				String name = jObject.getString("name");

				MainActivity.getInstance().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 = jObject.getString("videoUrl");

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

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

				MainActivity.getInstance().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 = jObject.getString("name");
				String title = jObject.getString("title");
				String description = jObject.getString("description");
				int hidden = jObject.getInt("hidden");

				MainActivity.getInstance().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 = jObject.getString("videoUrl");
				String name = jObject.getString("name");

				MainActivity.getInstance().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 = jObject.getString("name");
					int type = jObject.getInt("type");
					String title = jObject.getString("title");
					String content = jObject.getString("content");
					double geoLat = jObject.getDouble("geoLat");
					double geoLon = jObject.getDouble("geoLon");
					String address = jObject.getString("address");
					String phone = jObject.getString("phone");
					String externalLink = jObject.getString("externalLink");
					String externalLinkText = jObject.getString("externalLinkText");
					Date dateTime = ArticleManager.iso8601Format.parse(jObject.getString("dateTime"));
					int hidden = jObject.getInt("hidden");

					MainActivity.getInstance().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 = jObject.getString("name");
				String title = jObject.getString("title");
				String description = jObject.getString("description");
				int hidden = jObject.getInt("hidden");
				int geoCategory = jObject.getInt("geoCategory");
				int main = jObject.getInt("main");

				MainActivity.getInstance().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 = jObject.getString("albumName");
				String articleName = jObject.getString("articleName");

				MainActivity.getInstance().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 = jObject.getString("channelName");
				String articleName = jObject.getString("articleName");

				MainActivity.getInstance().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 = jObject.getString("articleName");
				String journalName = jObject.getString("journalName");

				MainActivity.getInstance().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 = jObject.getString("name");
				String textEn = jObject.getString("textEn");
				String textRu = jObject.getString("textRu");
				String textZh = jObject.getString("textZh");
				String textEnUp = jObject.getString("textEnUp");
				String textRuUp = jObject.getString("textRuUp");
				String textZhUp = jObject.getString("textZhUp");

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

			} // End Loop

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

}