package com.yuji.ec;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yuji.ec.common.CommonUtil;
import com.yuji.ec.common.Constant;
import com.yuji.ec.db.Note;
import com.yuji.ec.db.NoteDao;
import com.yuji.ec.db.NoteListItem;
import com.yuji.ec.utility.BaseActivity;
import com.yuji.ec.utility.EditPrefUtil;
import com.yuji.ec.utility.NoteComparator;

public class EverClipActivity extends BaseActivity {
	private static final String ACTION_INTERCEPT = "com.adamrocker.android.simeji.ACTION_INTERCEPT";
	private static final String REPLACE_KEY = "replace_key";
	private final static String NL = System.getProperty("line.separator");

	private EditPrefUtil pref = new EditPrefUtil(this);

	private LinearLayout layoutView = null;
	private TextView messageText = null;
	private ListView listView = null;
	private Button closeButton = null;

	private static boolean isInit = true;
	private boolean isEmpty = true;
	private boolean isVisible = false;

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (action.compareTo(Constant.ACTION_UPDATE) == 0) {
				updateList();
				listView.invalidate();

				setStatus();

				if (isVisible) {
					Toast toast = Toast.makeText(EverClipActivity.this,
							getString(R.string.toastUpdateList),
							Toast.LENGTH_SHORT);
					toast.show();
				}
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constant.ACTION_UPDATE);
		registerReceiver(receiver, intentFilter);

		layoutView = (LinearLayout) this.findViewById(R.id.mainLayout);
		messageText = (TextView) this.findViewById(R.id.mainConfirmDeleteMsg);
		listView = (ListView) this.findViewById(R.id.mainView);
		closeButton = (Button) this.findViewById(R.id.mainCloseButton);

		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				listViewOnItemClickListener(parent, view, position, id);
			}
		});
		closeButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				closeButtonOnClick();
			}
		});

		updateList();

		setStatus();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		updateList();

		setStatus();
	}

	@Override
	protected void onStart() {
		super.onStart();

		isVisible = true;
		if (isEmpty) {
			if (isInit) {
				Intent intent = new Intent(this,
						(Class<?>) SettingActivity.class);
				startActivityForResult(intent, 0);

				isInit = false;
			} else {
				finish();
				isInit = true;
			}
		}
	}

	@Override
	protected void onPause() {
		isVisible = false;

		super.onPause();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean ret = super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, Menu.FIRST, Menu.NONE, R.string.mainMenuSetting);
		return ret;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		try {
			switch (item.getItemId()) {
			case Menu.FIRST:
				intent = new Intent(this, (Class<?>) SettingActivity.class);
				startActivityForResult(intent, 0);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			terminate(e);
		}
		return super.onOptionsItemSelected(item);
	}

	private void listViewOnItemClickListener(AdapterView<?> parent, View view,
			int position, long id) {
		ListView listView = (ListView) parent;
		NoteListItem item = (NoteListItem) listView.getItemAtPosition(position);

		String result = item.getTitle();

		Intent data = new Intent();
		data.putExtra(REPLACE_KEY, result);
		setResult(RESULT_OK, data);
		finish();
	}

	private void closeButtonOnClick() {
		finish();
	}

	private void updateList() {
		Intent it = getIntent();
		String action = it.getAction();
		if (action != null && ACTION_INTERCEPT.equals(action)) {
			String str = it.getStringExtra(REPLACE_KEY);
			if (CommonUtil.isNull(str)) {
				layoutView.setVisibility(View.GONE);
				str = null;
			} else {
				messageText.setText(str);
			}
			updateList(str);
		} else {
			Intent intent = new Intent(this, (Class<?>) SettingActivity.class);
			startActivityForResult(intent, 0);
		}
	}

	private void updateList(String str) {
		List<NoteListItem> list = getNoteList(str);
		if (list == null) {
			terminate(null);
			return;
		}

		NoteListViewArrayAdapter adapter = new NoteListViewArrayAdapter(this,
				R.layout.simple_list_item_1, list);
		listView.setAdapter(adapter);
	}

	private List<NoteListItem> getNoteList(String str) {
		int noteOrder = pref.getInt(Constant.PREF_NOTE_ORDER,
				Constant.NOTE_ORDER_CREATE);

		NoteDao dao = (NoteDao) NoteDao.getInstance();

		List<Note> list = dao.search();
		if (list == null) {
			return null;
		}
		isEmpty = (list.size() <= 0) ? true : false;
		sortList(list);

		List<NoteListItem> listItem = new ArrayList<NoteListItem>();
		String oldTitle = "";
		NoteListItem item;
		int len = (str != null) ? str.length() : -1;

		for (Note note : list) {
			if (str != null) {
				String title = note.getText();
				if (title.length() < len) {
					continue;
				}
				if (!title.substring(0, len).equals(str)) {
					continue;
				}
			}

			String title = " ";
			String s;
			long l;
			switch (noteOrder) {
			case Constant.NOTE_ORDER_CREATE:
				l = note.getCreated();
				title = DateUtils
						.formatDateTime(this, l, DateUtils.FORMAT_SHOW_YEAR
								| DateUtils.FORMAT_SHOW_DATE);
				break;
			case Constant.NOTE_ORDER_UPDATE:
				l = note.getUpdated();
				title = DateUtils
						.formatDateTime(this, l, DateUtils.FORMAT_SHOW_YEAR
								| DateUtils.FORMAT_SHOW_DATE);
				break;
			case Constant.NOTE_ORDER_TEXT:
				s = note.getText();
				if (s.length() > 0) {
					title = s.substring(0, 1);
				}
				break;
			}
			if (!title.equals(oldTitle)) {
				item = new NoteListItem(title, null);
				listItem.add(item);
				oldTitle = title;
			}

			String text = note.getText();
			text = text.replace(NL, " ");

			Note n = new Note(note.getGuid(), text, note.getCreated(),
					note.getUpdated());
			item = new NoteListItem(null, n);
			listItem.add(item);
		}
		return listItem;
	}

	private void sortList(List<Note> list) {
		int noteOrder = pref.getInt(Constant.PREF_NOTE_ORDER,
				Constant.NOTE_ORDER_CREATE);

		int orderBy = pref.getInt(Constant.PREF_NOTE_ORDER_BY,
				Constant.NOTE_ORDER_BY_ASC);

		NoteComparator comp = new NoteComparator(noteOrder, orderBy);
		Collections.sort(list, comp);
	}

	private void setStatus() {

	}

	public static void init(boolean flag) {
		isInit = flag;
	}
}