package it.megaforum.megaapp;

import it.megaforum.megaapp.db.DatabaseHelperStorici;
import it.megaforum.megaapp.db.TopicStorici;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.TextView;

public class FragmentStorici extends ListFragment implements OnScrollListener {
	private SharedPreferences prefs;
	private Editor prefsEditor;
	private DatabaseHelperStorici dbHelper;
	private MegaHandler handler;
	private FragmentActivity activity;
	private RemoveWindow removeWindow;
	private WindowManager windowmgr;
	private TextView Overlay;
	private boolean isShowing;
	public boolean Ready = false;
	public static boolean isForeground = false;
	private char PrevLetter = Character.MIN_VALUE;
	private static final String STORICI_ORDERBY1 = "Storici Orderby1";
	private static final String STORICI_ORDERBY2 = "Storici Orderby2";

	private final class RemoveWindow implements Runnable {
		@Override
		public void run() {
			removeWindow();
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = (FragmentActivity) activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		handler = new MegaHandler(this);
		removeWindow = new RemoveWindow();
		setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container == null) {
			return null;
		}
		View view = super.onCreateView(inflater, container, savedInstanceState);
		Overlay = (TextView) inflater.inflate(R.layout.list_overlay, null);
		Overlay.setVisibility(View.INVISIBLE);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		ListView list = getListView();
		list.setCacheColorHint(0);
		int dip = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				5, getResources().getDisplayMetrics());
		list.setPadding(0, 0, dip, 0);
		list.setPersistentDrawingCache(ViewGroup.PERSISTENT_ALL_CACHES);
		list.setOnScrollListener(this);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		dbHelper = new DatabaseHelperStorici(activity);
		prefs = PreferenceManager.getDefaultSharedPreferences(activity);
		windowmgr = (WindowManager) activity
				.getSystemService(Context.WINDOW_SERVICE);
		handler.post(new Runnable() {
			@Override
			public void run() {
				LayoutParams lp = new WindowManager.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
						LayoutParams.TYPE_APPLICATION,
						LayoutParams.FLAG_NOT_TOUCHABLE
								| LayoutParams.FLAG_NOT_FOCUSABLE,
						PixelFormat.TRANSLUCENT);
				windowmgr.addView(Overlay, lp);
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
		initAdapter();
		registerForContextMenu(getListView());
	}

	@Override
	public void onPause() {
		super.onPause();
		removeWindow();
		unregisterForContextMenu(getListView());
		Ready = false;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		windowmgr.removeView(Overlay);
		Ready = false;
		dbHelper.close();
	}

	@Override
	public void onDetach() {
		super.onDetach();
		activity = null;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.megaoptionsmenu, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		prefsEditor = prefs.edit();
		String orderBy1 = prefs.getString(STORICI_ORDERBY1, TopicStorici._ID);
		String orderBy2 = prefs.getString(STORICI_ORDERBY2, "DESC");
		int flags = 0;
		switch (item.getItemId()) {
		case R.id.menutitolo:
			if (orderBy1.equals(TopicStorici.TITOLO)) {
				if (orderBy2.equals("DESC")) {
					orderBy2 = "ASC";
				} else {
					orderBy2 = "DESC";
				}
			} else {
				orderBy2 = "ASC";
			}
			orderBy1 = TopicStorici.TITOLO;
			flags = WorkingThread.FLAG_ORDERBYTITOLO;
			break;
		case R.id.menudata:
			if (orderBy1.equals(TopicStorici.URL)) {
				if (orderBy2.equals("DESC")) {
					orderBy2 = "ASC";
				} else {
					orderBy2 = "DESC";
				}
			} else {
				orderBy2 = "ASC";
			}
			orderBy1 = TopicStorici.URL;
			break;
		case R.id.menuid:
			if (orderBy1.equals(TopicStorici._ID)) {
				if (orderBy2.equals("DESC")) {
					orderBy2 = "ASC";
				} else {
					orderBy2 = "DESC";
				}
			} else {
				orderBy2 = "ASC";
			}
			orderBy1 = TopicStorici._ID;
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		new Thread(new WorkingThread(handler, dbHelper, flags, 0, orderBy1
				+ " " + orderBy2)).start();
		prefsEditor.putString(STORICI_ORDERBY1, orderBy1).putString(
				STORICI_ORDERBY2, orderBy2);
		prefsEditor.commit();
		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		activity.getMenuInflater().inflate(R.menu.megacontextmenu, menu);
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
		menu.setHeaderTitle(cursor.getString(cursor
				.getColumnIndex(TopicStorici.TITOLO)));
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.menuapri:
			apriTopicStorico(info.position);
			return true;
		case R.id.menucondividi:
			final Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/plain");
			Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
			String messaggio = cursor.getString(cursor
					.getColumnIndex(TopicStorici.TITOLO))
					+ " http://megaforum.freeforumzone.leonardo.it/discussione.aspx?idd="
					+ cursor.getString(cursor.getColumnIndex(TopicStorici.URL));
			intent.putExtra(Intent.EXTRA_TEXT, messaggio);
			startActivity(Intent.createChooser(intent,
					getString(R.string.condividi)));
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		apriTopicStorico(position);
	}

	private void apriTopicStorico(int position) {
		Cursor cursor = (Cursor) getListAdapter().getItem(position);
		String url = cursor.getString(cursor.getColumnIndex(TopicStorici.URL));
		url = cambiaUrl(prefs, url);
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
		startActivity(intent);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (Ready && isForeground) {
			Cursor cursor = (Cursor) view.getItemAtPosition(firstVisibleItem);
			char firstLetter;
			try {
				firstLetter = cursor.getString(
						cursor.getColumnIndex(TopicStorici.TITOLO)).charAt(0);
			} catch (CursorIndexOutOfBoundsException e) {
				firstLetter = Character.MIN_VALUE;
			}
			if (!isShowing && firstLetter != PrevLetter
					&& firstLetter != Character.MIN_VALUE) {
				isShowing = true;
				Overlay.setVisibility(View.VISIBLE);
			}
			Overlay.setText(((Character) firstLetter).toString());
			handler.removeCallbacks(removeWindow);
			handler.postDelayed(removeWindow, 3000);
			PrevLetter = firstLetter;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}

	private void removeWindow() {
		if (isShowing) {
			isShowing = false;
			Overlay.setVisibility(View.INVISIBLE);
		}
	}

	private void initAdapter() {
		String orderBy1 = prefs.getString(STORICI_ORDERBY1, TopicStorici._ID);
		int flags = 0;
		if (orderBy1.equals(TopicStorici.TITOLO)) {
			flags |= WorkingThread.FLAG_ORDERBYTITOLO;
		}
		new Thread(new WorkingThread(handler, dbHelper, flags, 0, orderBy1
				+ " " + prefs.getString(STORICI_ORDERBY2, "ASC"))).start();
	}

	public static String cambiaUrl(SharedPreferences prefs, String url) {
		while (url.length() > 1 && url.charAt(0) == '0') {
			url = url.substring(1);
		}
		int versione = Integer.valueOf(prefs
				.getString(OpzioniActivity.VERSIONE_PREF,
						OpzioniActivity.VERSIONE_DEFAULT));
		switch (versione) {
		case 1:
		default:
			return "http://megaforum.freeforumzone.leonardo.it/discussione.aspx?idd="
					+ url;
		case 2:
			return "http://megaforum.freeforumzone.leonardo.it/mobile/discussione.aspx?idd="
					+ url;
		case 3:
			return "http://megaforum.freeforumzone.leonardo.it/lofi/D" + url
					+ ".html";
		}
	}
}