package jp.agentec.abook.abv.ui.viewer.view.action;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.graphics.Point;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewParent;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.data.dao.AbstractDao;
import jp.agentec.abook.abv.bl.data.dao.ContentMemoDao;
import jp.agentec.abook.abv.bl.dto.ContentMemoDto;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.MemoLogic;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.dialog.ABookAlertDialog;
import jp.agentec.abook.abv.ui.common.util.AlertDialogUtil;
import jp.agentec.abook.abv.ui.common.util.ClipboardUtil;
import jp.agentec.abook.abv.ui.common.util.DisplayUtil;
import jp.agentec.abook.abv.ui.common.view.ABVPopupListWindow;
import jp.agentec.abook.abv.ui.viewer.view.ActionMemoIcon;
import jp.agentec.abook.abv.ui.viewer.view.ZoomRelativeLayout;
import jp.agentec.adf.util.DateTimeUtil;

public class MemoManager {
	private static final String TAG = "MemoManager";

	public static final int ICON_ENABLE = 1;
	public static final int ICON_DISABLE = 0;
	public static final int ICON_DELETE = -1;
	
	private static ContentMemoDao contentMemoDao = AbstractDao.getDao(ContentMemoDao.class);
	private static MemoLogic memoLogic = AbstractLogic.getLogic(MemoLogic.class);

	private static final int ICON_WIDTH = 32;
	private static final int ICON_HEIGHT = 32;

	public static void showMemoDialog(final RelativeLayout rootLayout, final ContentMemoDto memoDto) {
		final Dialog memoDialog = new Dialog(rootLayout.getContext());
		memoDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		memoDialog.setCanceledOnTouchOutside(true);
		
		LayoutInflater inflater = (LayoutInflater) rootLayout.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View contentView = inflater.inflate(R.layout.memo_popup, null);
		memoDialog.setContentView(contentView);
		
		final EditText memoText = (EditText) contentView.findViewById(R.id.memoText);
		final Button btnDelete = (Button) contentView.findViewById(R.id.memo_delete);
		final Button btnSave = (Button) contentView.findViewById(R.id.memo_save);
		final Button btnCancel = (Button) contentView.findViewById(R.id.memo_cancel);
		final ImageView abookmark = (ImageView) contentView.findViewById(R.id.abookmark);
		
		// 新規
		if (memoDto.memoId == null) {
			btnSave.setVisibility(View.VISIBLE);
			btnCancel.setVisibility(View.VISIBLE);
			btnDelete.setVisibility(View.GONE);
			abookmark.setVisibility(View.GONE);
			memoText.setFocusable(true);
			memoText.setFocusableInTouchMode(true);
		}
		
		// 保存ボタン
		btnSave.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 保存処理
				memoDto.memo = (memoText.getText().toString());
				memoDto.updateDate = DateTimeUtil.getCurrentUTCDate();
				
				// DBデータ更新
				//noinspection VariableNotUsedInsideIf
				if (memoDto.memoId == null) {
					memoDto.insertDate = DateTimeUtil.getCurrentUTCDate();
					memoLogic.insertContentMemo(memoDto);
					addMemoIcon(rootLayout, memoDto);
				} else {
					contentMemoDao.updateMemo(memoDto);
				}
				
				// 編集モード終了
				memoText.setFocusable(false);
				memoText.setFocusableInTouchMode(false);
				
				btnSave.setVisibility(View.GONE);
				btnCancel.setVisibility(View.GONE);
				btnDelete.setVisibility(View.VISIBLE);
				abookmark.setVisibility(View.VISIBLE);
//				toggleKeyboard(false, memoText);
			}
		});
		
		
		// 削除ボタン
		btnDelete.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showDeleteDialog(rootLayout, memoDto);
				memoDialog.dismiss();
			}
		});
		
		// メモテキスト
		memoText.setText(memoDto.memo);
		memoText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (memoText.isFocusable()) {
                    return;
                }
				
				Logger.d(TAG, "EditText onClick");
				memoText.setFocusable(true);
				memoText.setFocusableInTouchMode(true);
				memoText.requestFocus();
				
				btnSave.setVisibility(View.VISIBLE);
				btnCancel.setVisibility(View.VISIBLE);
				btnDelete.setVisibility(View.GONE);
				abookmark.setVisibility(View.GONE);
			}
		});
		memoText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					//完了ボタンが押された
				}
				return false;
			}
		});
		
		// Cancel
		btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 編集モード終了(キーボードを閉じる)
				memoText.setFocusable(false);
				memoText.setFocusableInTouchMode(false);
				
				if (memoDto.memoId == null) {
					// 新規の場合、キャンセルしたため、画面を閉じる
					memoDialog.dismiss();
					return;
				}
				
				btnSave.setVisibility(View.GONE);
				btnCancel.setVisibility(View.GONE);
				btnDelete.setVisibility(View.VISIBLE);
				abookmark.setVisibility(View.VISIBLE);
			}
		});
		memoText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				Logger.d(TAG, "memoText.onFocusChange:%s", hasFocus);
				toggleKeyboard(hasFocus, memoText, rootLayout.getContext());
				memoDialog.setCanceledOnTouchOutside(!hasFocus);
			}
		});
		
		memoDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				Logger.d(TAG, "setOnDismissListener");
//				toggleKeyboard(false, memoText, context);
			}
		});
		
		memoDialog.setOnShowListener(new OnShowListener() {
			@Override
			public void onShow(DialogInterface dialog) {
				if (memoDto.memoId == null) {
					// 新規の場合
					toggleKeyboard(true, memoText, rootLayout.getContext());
				}
			}
		});
		
		memoDialog.show();
	}
	
	public static boolean addMemoIcon(final RelativeLayout rootLayout, final ContentMemoDto dto) {
    	// アイコン追加
		final ActionMemoIcon imgIcon = new ActionMemoIcon(rootLayout.getContext());
    	imgIcon.memoId = dto.memoId;
    	if (dto.delFlg) {
    		// 切り取りの対象
    		imgIcon.setEnabled(false);
    	}
    	RelativeLayout.LayoutParams param1_;
    	float density = rootLayout.getContext().getResources().getDisplayMetrics().density;
    	param1_ = new RelativeLayout.LayoutParams((int)(ICON_WIDTH * density), (int)(ICON_HEIGHT  * density));
    	param1_.setMargins(dto.viewX, dto.viewY, 0, 0);
    	rootLayout.addView(imgIcon, param1_);
    	imgIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showMemoDialog(rootLayout, dto);
			}
		});
    	imgIcon.setOnLongClickListener(new View.OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				final Context context = rootLayout.getContext();
				final ABVPopupListWindow popup = ((ZoomRelativeLayout) rootLayout).createSimplePopupWindow();
				popup.setWidth(200);
				popup.setRepresentNames(new String[] { context.getResources().getString(R.string.cut),
								context.getResources().getString(R.string.copy),
								context.getResources().getString(R.string.delete)});
				popup.getListView().setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
						Logger.d(TAG, "ActionMemoImageView:dto:%s, %s, id=%s",dto.axisX, dto.axisY, dto.contentId);
						if (position == 2) {
							// delete
							showDeleteDialog(rootLayout, dto);
							
						} else {
							// 既存データをクリアする
							contentMemoDao.clearCopiedMemo();
							if (position == 1) {
								// copy
								// 保存処理
					   		 	// DBデータ更新
								boolean result = memoLogic.setContentMemoToCopy(dto, false);
								Logger.d(TAG, "memo copy = " + result);
							} else {
								// cut
				   		 		boolean result = memoLogic.setContentMemoToCopy(dto, true);
				   		 		imgIcon.setEnabled(false);
				   		 		Logger.d(TAG, "memo cut = " + result);
							}
							// ClipBoardへコピーする
							ClipboardUtil.setText(context, dto.memo);
							
						}
						popup.dismiss();
					}
				});
				
				// 端末の端っこを押した場合、表示位置をずらすための処理
				int[] location = new int[2];
				v.getLocationInWindow(location);
				Logger.w("getLocationInWindow=" + location[0] + ", " + location[1]);
				
				// 選択されたポジション
				int popX = location[0];
				int popY = location[1];
				
				Point outSize = DisplayUtil.getDisplaySize(context);
				
				if (popX > outSize.x - 200) {
					popX -= 200;
				}
				if (popY > outSize.y - 250) {
					popY -= 250;
				}
				
				if (location[0] != popX || location[1] != popY) {
					popup.showAtLocation(rootLayout, Gravity.NO_GRAVITY, popX, popY);
				} else {
					popup.showAsDropDown(v);
				}
				return true;
			}
		});
		return true;
    }
	
	private static void toggleKeyboard(boolean isShow, View v, Context context) {
		InputMethodManager im = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (isShow) {
			Logger.d(TAG, "toggleKeyboard show");
			im.showSoftInput(v, InputMethodManager.SHOW_FORCED);
		} else {
			boolean result = im.hideSoftInputFromWindow(v.getWindowToken(), 0);
			Logger.d(TAG, "toggleKeyboard hide:%s, VIew=%s", result, v);
		}
		
	}

	public static void showDeleteDialog(final RelativeLayout rootLayout, final ContentMemoDto mMemoDto) {
		Context context = rootLayout.getContext();
		
		ABookAlertDialog dialogDelete = AlertDialogUtil.deleteContentAlertDialog(context, R.string.delete_message);
		dialogDelete.setTitle(R.string.memo);

		dialogDelete.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {
				// 処理なし
			}
		});
		dialogDelete.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {
				// DBデータ削除
		 		contentMemoDao.deleteMemo(mMemoDto);
		 		setIconStatus(rootLayout, mMemoDto.memoId, ICON_DELETE);
			}
		});
		dialogDelete.show();
	}
	
	/**
	 * 対象のmemoのステータスを変更する
	 * @param rootLayout RelativeLayout
	 * @param memoId
	 * @param status ICON_ENABLE, ICON_DISABLE, ICON_DELETE
	 */
	public static void setIconStatus(RelativeLayout rootLayout, String memoId, int status) {
		
		if (setIconStatusOnMine(rootLayout, memoId, status)) {
			return;
		}
 		
 		// 同じページに対象のメモがなかった場合
		ViewParent p = rootLayout.getParent().getParent();
		if (p instanceof RelativeLayout == false) {
			return;
		}
		RelativeLayout contentWrapLayout = (RelativeLayout) p;
		for (int i = 0; i < contentWrapLayout.getChildCount(); i++) {
			RelativeLayout pageLayout = (RelativeLayout) contentWrapLayout.getChildAt(i);
			for (int k = 0; k < pageLayout.getChildCount(); k++) {
				View v = pageLayout.getChildAt(k);
				if (v instanceof ZoomRelativeLayout) {
					if (setIconStatusOnMine((RelativeLayout)v, memoId, status)) {
						return;
					}
				}
			}
			
		}
	}
	
	private static boolean setIconStatusOnMine(RelativeLayout rootLayout, String memoId, int status) {
		for (int i = 0; i < rootLayout.getChildCount(); i++) {
 			View v = rootLayout.getChildAt(i);
			if (v instanceof ActionMemoIcon) {
				ActionMemoIcon icon = (ActionMemoIcon)v;
				if (icon.memoId.equals(memoId)) {
					if (status == ICON_DELETE) {
						rootLayout.removeView(v);
					} else if (status == ICON_DISABLE) {
						v.setEnabled(false);
					} else if (status == ICON_ENABLE) {
						v.setEnabled(true);
					}
					Logger.d(TAG, "setIconStatusOnMine=%s, status=%s", memoId, status);
					return true;
				}
			}
		}
		return false;
	}
}
