package jp.agentec.abook.abv.ui.viewer.activity;

import jp.agentec.abook.abv.bl.common.ABVEnvironment;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.websocket.MeetingManager;
import jp.agentec.abook.abv.cl.util.BitmapUtil;
import jp.agentec.abook.abv.cl.util.ContentLogUtil;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.activity.ABVContentViewActivity;
import jp.agentec.abook.abv.ui.common.util.ABVToastUtil;
import jp.agentec.abook.abv.ui.home.helper.ActivityHandlingHelper;
import jp.agentec.abook.abv.ui.viewer.view.ActionZoomLayout;

import org.json.adf.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class PreviewActivity extends ABVContentViewActivity {
	private static final String TAG = "PreviewActivity";
	private ViewFlipper mViewFlipper;
	private LinearLayout[] mFlipperLayout;
	private LinearLayout mLayoutThumbnail;
	private ActionZoomLayout mZoomLayout;
	private int mPosition;   //表示画像番号
	private int mMaxImg;     //画像数
	private float mStartX;
	private static final int THUMBNAIL_WIDTH = 100;
	private static final int THUMBNAIL_HEIGHT = 100;
	private String[] mFilePath;
	private int mHistoryImageIndex[] = new int[2];
	private int objectLogId;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        Logger.i(TAG, "onCreate");
        super.onCreate(savedInstanceState);
	    requestWindowFeature(Window.FEATURE_NO_TITLE);   //タイトルバー非表示
	    int wrapContent = ViewGroup.LayoutParams.WRAP_CONTENT;
	    int matchParent = ViewGroup.LayoutParams.MATCH_PARENT;
	    
	    mZoomLayout = new ActionZoomLayout(this);
	    mZoomLayout.setGravity(Gravity.CENTER);
	    LinearLayout.LayoutParams paramMain = new LinearLayout.LayoutParams(matchParent, matchParent);
	    mZoomLayout.addView(getLayoutInflater().inflate(R.layout.ac_preview, null), paramMain);
    	setContentView(mZoomLayout);
    	
	    mMaxImg = 0;
	    // 画像数の取得
	    Intent intent = getIntent();
	    if (objectId != -1 || ABVEnvironment.getInstance().disableLogSend) {
			// アクションとして起動された場合ログは記録しない 
			readingLogFlg = false;
		}
	    objectLogId = intent.getIntExtra("objectLogId", -1);
	    mPosition = intent.getIntExtra("Position", 0);
		
	    for (int i = 0; i < 8; i++) {
	    	if (intent.getStringExtra("FILEPATH" + (i + 1)) == null) {
	    		break;
	    	} else {
	    		mMaxImg++;
	    	}
	    }
	    
	    mViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipperPreview);
	    mLayoutThumbnail = (LinearLayout)findViewById(R.id.layoutThumbnail);
	    mFlipperLayout = new LinearLayout[mMaxImg];
	    mFilePath = new String[mMaxImg];
	    ImageButton[] imgBtn = new ImageButton[mMaxImg];   // サムネイル
	    for (int i = 0; i < mMaxImg; i++) {	    	
	    	imgBtn[i] = new ImageButton(this);
	    	imgBtn[i].setScaleType(ScaleType.CENTER_INSIDE);
	    	imgBtn[i].setAdjustViewBounds(true);
	        
	    	// 画像FilePath取得
	    	mFilePath[i] = intent.getStringExtra("FILEPATH" + (i + 1));
	    	if (mFilePath[i] == null) {
	    		ABVToastUtil.showMakeText(getApplication(), "Error: No Image File", Toast.LENGTH_SHORT);
	    		finishActivity();
				return;
	    	} else {
	    		float tmpDensity = getResources().getDisplayMetrics().density;
				Bitmap resized = BitmapUtil.getResizedBitmap(mFilePath[i], (int)(50 * tmpDensity + 0.5f), (int)(50 * tmpDensity + 0.5f), Config.RGB_565, false);
				imgBtn[i].setImageBitmap(resized);
	    	}	    	
	    	mFlipperLayout[i] = new LinearLayout(this);
	    	mFlipperLayout[i].setGravity(Gravity.CENTER);
	    	LinearLayout.LayoutParams paramFlipperLayout = new LinearLayout.LayoutParams(matchParent, matchParent);
	    	mViewFlipper.addView(mFlipperLayout[i], paramFlipperLayout);

	    	LinearLayout.LayoutParams paramThumbnail = new LinearLayout.LayoutParams(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
	        mLayoutThumbnail.addView(imgBtn[i], paramThumbnail);
	        setBtnClick(imgBtn[i], i);	        
	    }
	    ImageView flipperImageView = new ImageView(this);
    	flipperImageView.setScaleType(ScaleType.CENTER_INSIDE);
    	flipperImageView.setAdjustViewBounds(true);
	    flipperImageView.setImageURI(Uri.parse(mFilePath[0]));
	    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(wrapContent, wrapContent);
	    mFlipperLayout[0].addView(flipperImageView, param);
	    mHistoryImageIndex[0] = 1;
	
	    mViewFlipper.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (mZoomLayout.isZooming() == false) {
					if (event.getPointerCount() == 1) {
						mViewFlipper.getParent().requestDisallowInterceptTouchEvent(true);
						switch (event.getAction()) {
						case MotionEvent.ACTION_DOWN:
							mStartX = event.getX();
							break;
						case MotionEvent.ACTION_UP:
							if (mStartX > event.getX()) {
								if ((mPosition < (mMaxImg - 1)) && (mStartX - event.getX()) > 50) {
									setRemoteEventPreview(mPosition + 1);
									goNext();       //次の画像を表示
								}
							} else if (mStartX < event.getX()) {
								if ((mPosition > 0) && (event.getX() - mStartX) > 50) {
									setRemoteEventPreview(mPosition - 1);
									goPrevious();   //前の画像を表示
								}
							}
							break;
						case MotionEvent.ACTION_MOVE:
						case MotionEvent.ACTION_CANCEL:
							break;
						}
						return true;
					} else {
						mZoomLayout.onTouchEvent(event);
					}
					return false;
				} else {
					mZoomLayout.onTouchEvent(event);
					return false;
				}
			}
		});
	    goIndex(mPosition);
	    
	    //***** 戻るボタン
        ImageButton imgBtnBack = (ImageButton) findViewById(R.id.imgBtnBack);
        imgBtnBack.setPadding(0, 0, 0, 0);
        imgBtnBack.setAdjustViewBounds(true);                //描画の縦横比を維持
        imgBtnBack.setScaleType(ScaleType.FIT_CENTER);       //拡大表示
		//noinspection deprecation(API16から非推奨になった。無視)
        imgBtnBack.setBackgroundDrawable(null);              //半透明表示
        imgBtnBack.setContentDescription(getResources().getString(R.string.cont_desc));
        imgBtnBack.setImageDrawable(getResources().getDrawable(android.R.drawable.btn_dialog));   //戻るボタン表示
        imgBtnBack.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	finishActivity();
	        }
		});
        
        // Activity登録
        ActivityHandlingHelper.getInstance().setObjectViewActivity(this);
    }
	
	private void setBtnClick(ImageButton imgBtn, int index) {
		final int index_ = index;
		imgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	if (mPosition != index_ && mZoomLayout.isZooming() == false) {
            		setRemoteEventPreview(index_);
            		goIndex(index_);
            	}
            }
        });
	}
	
	// 画像数を返す
	public int getMaxImg() {
		return mMaxImg;
	}
	
	// 選択画像を表示
	public void goIndex(int index) {
		if (mPosition > index) {
			mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.inslide_left));
			mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.outslide_right));
		} else {
			mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.inslide_right));
			mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.outslide_left));
		}
		setFlipperImage(index);
		mViewFlipper.setDisplayedChild(index);
	}
		
	// 次の画像を表示
	private void goNext() {
		mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.inslide_right));
		mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.outslide_left));
		setFlipperImage(mPosition + 1);
		mViewFlipper.showNext();
	}
	
	// 前の画像を表示
	private void goPrevious() {
		mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.inslide_left));
		mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.outslide_right));
		setFlipperImage(mPosition - 1);
		mViewFlipper.showPrevious();
	}
	
    private void setFlipperImage(int index) {
    	ImageView flipperImageView = new ImageView(this);
    	flipperImageView.setScaleType(ScaleType.FIT_CENTER);   //CENTER_INSIDE
    	flipperImageView.setAdjustViewBounds(true);
    	flipperImageView.setImageURI(Uri.parse(mFilePath[index]));
		int MP = ViewGroup.LayoutParams.MATCH_PARENT;
		LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(MP, MP);
		mFlipperLayout[index].removeAllViews();
	    mFlipperLayout[index].addView(flipperImageView, param);
	    mPosition = index;
		removeFlipperImage(index + 1);
    }
    
	@Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
    		finishActivity();
	    } else  {
			return super.onKeyUp(keyCode, event);
		}
    	return false;
    }

	@Override
	protected void finishActivity() {
    	Intent intent = new Intent();
    	setResult(RESULT_OK, intent);
    	finish();
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    }
    
    private void removeFlipperImage(int index) {
    	int historyHitPosition = -1;
    	boolean historyMaxFlg = true;
    	for (int i = 0; i < mHistoryImageIndex.length; i++) {
    		if (mHistoryImageIndex[i] == index) {
    			historyHitPosition = i;
    			break;
    		} else if (mHistoryImageIndex[i] == 0) {
    			historyMaxFlg = false;
    			mHistoryImageIndex[i] = index;
    			break;
    		}
    	}
    	if (historyHitPosition > -1) {
    		for (int i = historyHitPosition; i < mHistoryImageIndex.length; i++) {
    			if ((i + 1) < mHistoryImageIndex.length) {
    				if (mHistoryImageIndex[i + 1] == 0) {
    					mHistoryImageIndex[i] = index;
    					break;
    				} else {
    					mHistoryImageIndex[i] = mHistoryImageIndex[i + 1];
    				}
    			} else {
    				mHistoryImageIndex[i] = index;
    			}
    		}
    	} else if (historyMaxFlg == true) {
    		mFlipperLayout[mHistoryImageIndex[0] - 1].removeAllViews();
    		for (int i = 0; i < mHistoryImageIndex.length; i++) {
    			if ((i + 1) < mHistoryImageIndex.length) {
    				mHistoryImageIndex[i] = mHistoryImageIndex[i + 1];
    			} else {
    				mHistoryImageIndex[i] = index;
    			}
    		}
       	} 	
    }

	private void setRemoteEventPreview(int index) {
        meetingManager = MeetingManager.getInstance();
        if (meetingManager.isSendable()) {
        	JSONObject json = new JSONObject();
			json.put(MeetingManager.IMAGE_INDEX, index);
        	meetingManager.sendWs(MeetingManager.CMD_IMAGEPREVIEWACTION, getContentId(), objectPageNumber, getObjectId(), json);
        }
	}

	@Override
	public void onResume() {
		Logger.i(TAG, "onResume");
		super.onResume();
		ContentLogUtil.getInstance().resumeObjectLog(getContentId(), objectLogId);
	}

	@Override
	protected void onStop() {
		super.onStop();
		ContentLogUtil.getInstance().endObjectLog(getContentId(), objectLogId);
	}
}