package fishrungames.bashgid;

import it.sephiroth.android.library.widget.AdapterView.OnItemClickListener;
import it.sephiroth.android.library.widget.HListView;

import java.util.ArrayList;

import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.api.IMapController;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;

import fishrungames.bashgid.OsmMapHolderFragment.NoInteractionOverlay;
import fishrungames.bashgid.core.ArticleManager;

import fishrungames.bashgid.core.DatabaseGetArticleTask;

import fishrungames.bashgid.core.ArticleManager.ArticleFullData;
import fishrungames.bashgid.core.PhotoManager.PhotoRecordData;
import fishrungames.networkutils.ImageManager;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.net.Uri;

import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import android.widget.Button;

import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ArticleFragment extends Fragment
{

	public static class ArticleLayoutElement
	{
		public int type; // 0 title; 1 text; 2 photo; 3 geotag; 4 photo_album; 5
							// button 6 phone
		public String value;

		public double geoLat;
		public double geoLon;

		public int albumPos;

		public ArticleLayoutElement(int type, String value)
		{
			this.type = type;
			this.value = value;
			this.geoLat = 0;
			this.geoLon = 0;
			this.albumPos = -1;
		}

		public ArticleLayoutElement(double geoLat, double geoLon)
		{
			this.type = 3;
			this.value = "";
			this.geoLat = geoLat;
			this.geoLon = geoLon;
			this.albumPos = -1;
		}

		public ArticleLayoutElement(int albumPos)
		{
			this.type = 4;
			this.value = "";
			this.geoLat = 0;
			this.geoLon = 0;
			this.albumPos = albumPos;
		}
	}

	public class MapOverlay extends org.osmdroid.views.overlay.Overlay
	{

		public MapOverlay(Context ctx)
		{
			super(ctx);
		}

		@Override
		protected void draw(Canvas arg0, MapView arg1, boolean arg2)
		{

		}

		@Override
		public boolean onTouchEvent(final MotionEvent event, final MapView mapView)
		{
			MainActivity.getInstance().SetLastArticleName(articleName);
			
			if (event.getAction() == MotionEvent.ACTION_UP)
			{
				MainActivity.getInstance().OpenMapScreen(article, MainActivity.TAG_BACK_TO_ARTICLEFRAGMENT);
			}
			return true;
		}

	}

	ListView listView;
	ListAdapter listAdapter;

	ProgressBar progressBar;

	String articleName;
	ArticleFullData article;
	ArrayList<ArticleLayoutElement> articleLayout = new ArrayList<ArticleLayoutElement>();

	public ArticleFragment()
	{
		articleName = "";
		article = null;
	}

	public ArticleFragment(String articleName)
	{
		this.articleName = articleName;
		RestoreArticle();
		ReloadLayout();
	}

	public ArticleFragment(ArticleFullData article)
	{
		this.articleName = article.name;
		this.article = article;
		ReloadLayout();
	}

	@Override
	public void onSaveInstanceState(final Bundle outState)
	{
		super.onSaveInstanceState(outState);
		outState.putString("articleName", articleName);
	}

	public void RestoreArticle()
	{
		DatabaseGetArticleTask task = new DatabaseGetArticleTask();

		task.mHandler = MainActivity.getInstance().mHandler;

		task.execute(articleName);
	}

	public void ReloadLayout()
	{
		articleLayout.clear();

		if (article != null)
		{

			articleLayout.add(new ArticleLayoutElement(0, article.title));

			PhotoRecordData zeroPhoto = null;

			if (article.albumArr.size() > 0)
			{
				if (article.albumArr.get(0).photoRecordArr.size() > 0)
				{
					zeroPhoto = article.albumArr.get(0).photoRecordArr.get(0);
				}

			}

			if (zeroPhoto != null)
			{
				articleLayout.add(new ArticleLayoutElement(2, zeroPhoto.imageUrl));
			}

			articleLayout.add(new ArticleLayoutElement(1, article.content));

			if (article.phone.length() > 0)
			{
				articleLayout.add(new ArticleLayoutElement(6, article.phone));

			}

			if (article.geoLat != 0 && article.geoLon != 0)
			{
				articleLayout.add(new ArticleLayoutElement(article.geoLat, article.geoLon));
			}

			for (int i = 0; i < article.albumArr.size(); i++)
			{
				articleLayout.add(new ArticleLayoutElement(i));
			}

			if (article.externalLink.length() > 0)
			{
				articleLayout.add(new ArticleLayoutElement(5, article.externalLink));
			}

		}
	}

	public void SetArticle(ArticleFullData article)
	{
		progressBar.setVisibility(View.GONE);

		this.article = article;

		ReloadLayout();

		listAdapter.notifyDataSetChanged();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{

		if (savedInstanceState != null)
		{
			articleName = savedInstanceState.getString("articleName");
			RestoreArticle();
			ReloadLayout();
		}

		View rootView = inflater.inflate(R.layout.fragment_article_page, container, false);

		progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);

		progressBar.setVisibility(View.VISIBLE);

		listView = (ListView) rootView.findViewById(R.id.listView);

		listAdapter = new ListAdapter(getActivity());

		listView.setAdapter(listAdapter);

		return rootView;
	}

	public class ListAdapter extends BaseAdapter
	{
		private Context mContext;

		public ListAdapter(Context c)
		{
			mContext = c;
		}

		public int getCount()
		{
			return articleLayout.size();
		}

		public Object getItem(int position)
		{
			return null;
		}

		public long getItemId(int position)
		{
			return 0;
		}

		@Override
		public int getViewTypeCount()
		{
			return 7;
		}

		@Override
		public int getItemViewType(int position)
		{
			return articleLayout.get(position).type;

		}

		// create a new ImageView for each item referenced by the Adapter
		@SuppressLint("InflateParams")
		public View getView(final int position, View convertView, ViewGroup parent)
		{

			View view;
			if (convertView == null)
			{ // if it's not recycled, initialize some attributes
				if (getItemViewType(position) == 0 || getItemViewType(position) == 1)
				{
					LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.article_text_element, null);
				} else if (getItemViewType(position) == 2)
				{
					LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.article_photo_element, null);
				} else if (getItemViewType(position) == 3)
				{
					LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.article_geotag_element, null);
				} else if (getItemViewType(position) == 4)
				{
					LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.article_album_element, null);
				} else if (getItemViewType(position) == 5)
				{
					LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.article_button_element, null);
				} else
				// if (getItemViewType(position) == 6)
				{
					LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.article_phone_element, null);
				}
			} else
			{
				view = convertView;
			}

			if (getItemViewType(position) == 0)
			{
				TextView textView = (TextView) view.findViewById(R.id.dateTextView);

				textView.setText(articleLayout.get(position).value);

				if (article.type == ArticleManager.ARTICLE_TYPE_NEWS)
				{
					textView.setTextSize(getResources().getDimension(R.dimen.xlarge_text_size));
				} else
				{
					textView.setTextSize(getResources().getDimension(R.dimen.xxlarge_text_size));
				}

				textView.setTypeface(null, Typeface.BOLD);
				textView.setGravity(Gravity.CENTER_HORIZONTAL);

			} else if (getItemViewType(position) == 1)
			{
				TextView textView = (TextView) view.findViewById(R.id.dateTextView);

				textView.setText(articleLayout.get(position).value);

				textView.setTextSize(getResources().getDimension(R.dimen.article_content_text_size));
				textView.setTypeface(null, Typeface.NORMAL);
				textView.setGravity(Gravity.LEFT);

			} else if (getItemViewType(position) == 2)
			{
				TextView textView = (TextView) view.findViewById(R.id.dateTextView);
				ImageView imageView = (ImageView) view.findViewById(R.id.imageView);

				PhotoRecordData photo = MainActivity.getInstance().photoDataSource.GetPhotoByImageUrl(articleLayout.get(position).value);

				ImageManager.getInstance().ApplyImageToImageView(imageView, photo.imageUrl);

				textView.setText(photo.title);
			} else if (getItemViewType(position) == 3)
			{
				double geoLat = articleLayout.get(position).geoLat;
				double geoLon = articleLayout.get(position).geoLon;

				TextView addressTextView = (TextView) view.findViewById(R.id.addressTextView);
				TextView hintTextView = (TextView) view.findViewById(R.id.hintTextView);

				if (article.address.length() > 0)
				{
					addressTextView.setText(article.address);
					addressTextView.setVisibility(View.VISIBLE);

					hintTextView.setVisibility(View.VISIBLE);

					final String copied_text = getResources().getString(R.string.copied_text);

					addressTextView.setOnLongClickListener(new OnLongClickListener()
					{

						@Override
						public boolean onLongClick(View v)
						{

							if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
							{
								android.text.ClipboardManager clipboard = (android.text.ClipboardManager) MainActivity.getInstance().getSystemService(
										Context.CLIPBOARD_SERVICE);
								clipboard.setText(article.address);
							} else
							{
								android.content.ClipboardManager clipboard = (android.content.ClipboardManager) MainActivity.getInstance().getSystemService(
										Context.CLIPBOARD_SERVICE);
								android.content.ClipData clip = android.content.ClipData.newPlainText(copied_text, article.address);
								clipboard.setPrimaryClip(clip);
							}

							CharSequence text = getResources().getString(R.string.text_is_copied);
							Toast toast = Toast.makeText(MainActivity.getInstance(), text, Toast.LENGTH_SHORT);
							toast.show();

							return true;
						}

					});
					// editText.setKeyListener(null);

				} else
				{
					addressTextView.setVisibility(View.GONE);
					hintTextView.setVisibility(View.GONE);
				}

				MapView mapView = (MapView) view.findViewById(R.id.mapview);

				mapView.setMaxZoomLevel(20);
				mapView.setMinZoomLevel(4);

				// mapView.setBuiltInZoomControls(true);
				// mapView.setMultiTouchControls(true);

				IMapController mapController = mapView.getController();

				GeoPoint markerPoint = new GeoPoint(geoLat, geoLon);

				mapController.setZoom(16);
				mapController.animateTo(markerPoint);

				ResourceProxy resourceProxy = new DefaultResourceProxyImpl(getActivity());
				NoInteractionOverlay itemizedOverlay = new NoInteractionOverlay(getResources().getDrawable(R.drawable.russia_icon), resourceProxy);

				itemizedOverlay.addOverlayItem(markerPoint);

				mapView.getOverlays().add(itemizedOverlay);

				MapOverlay mapOverlay = new MapOverlay(getActivity());

				mapView.getOverlays().add(mapOverlay);

			} else if (getItemViewType(position) == 4)
			{

				TextView titleTextView = (TextView) view.findViewById(R.id.titleTextView);

				titleTextView.setText(article.albumArr.get(articleLayout.get(position).albumPos).title);

				TextView contentTextView = (TextView) view.findViewById(R.id.contentTextView);

				contentTextView.setText(article.albumArr.get(articleLayout.get(position).albumPos).description);

				HListView hListView = (HListView) view.findViewById(R.id.hListView);

				hListView.setAdapter(new MainPageHListViewAdapters.PhotoAlbumElementAdapter(getActivity(),
						article.albumArr.get(articleLayout.get(position).albumPos)));

				hListView.setOnItemClickListener(new OnItemClickListener()
				{

					@Override
					public void onItemClick(it.sephiroth.android.library.widget.AdapterView<?> parent, View view, int innerPosition, long id)
					{
						MainActivity.getInstance().SetLastArticleName(articleName);

						String albumName = article.albumArr.get(articleLayout.get(position).albumPos).name;

						MainActivity.getInstance().OpenPhotoScreen(albumName, innerPosition, MainActivity.TAG_BACK_TO_ARTICLEFRAGMENT);

					}
				});

			} else if (getItemViewType(position) == 5)
			{
				Button button = (Button) view.findViewById(R.id.button);

				if (article.externalLinkText.length() > 0)
				{
					button.setText(article.externalLinkText);
				} else
				{
					button.setText(R.string.go_to_website);
				}

				button.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						Intent i = new Intent(Intent.ACTION_VIEW);
						i.setData(Uri.parse(articleLayout.get(position).value));
						startActivity(i);
					}
				});
			} else if (getItemViewType(position) == 6)
			{
				Button button = (Button) view.findViewById(R.id.button);

				final String phone = article.phone;

				button.setText(phone);

				button.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						String uri = "tel:" + phone;
						Intent intent = new Intent(Intent.ACTION_DIAL);
						intent.setData(Uri.parse(uri));
						MainActivity.getInstance().startActivity(intent);
					}
				});
			}

			return view;
		}

	}
}
