package jp.sourceforge.nicoro;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;

import jp.gr.java_conf.shiseissi.commonlib.APILevelWrapper;
import jp.gr.java_conf.shiseissi.commonlib.ViewUtil;

public class PlayerInfoControllerManager {

    private static final int ANIM_TIME_PLAYER_CONTROLLER_IN = /*400*/ 200;
    private static final int ANIM_TIME_PLAYER_CONTROLLER_OUT = /*400*/ 100;

    private static final int MSG_ID_SET_ACTIONBAR_BACKGROUND = 0;

    public interface EventListener {
        void onPlayerControllerDisplayChanged(PlayerInfoControllerManager manager,
                boolean shown);
    }

    final PlayerInfoMiniLayout mPlayerInfoMini;
    final ViewGroup mPlayerController;
    private Object mActionBar;
    private ViewGroup mTitleCustomView;
    private VariableLabelView mTitleCustomViewTitle;
    private View mActionBarBackground;
    ViewGroup mPlayerInfoArea;

    private Drawable mPlayerInfoMiniBackground;

    private TranslateAnimation mAnimControllerIn;
    private TranslateAnimation mAnimControllerOut;

    float mTouchRangeWidth;
    float mTouchRangeHeight;
    private WindowManager mWindowManager;
    private InputMethodManager mInputMethodManager;

    private int mOrientation = Configuration.ORIENTATION_UNDEFINED;

    private EventListener mEventListener;

    private final GestureDetector mGestureDetector;
    private class CustomGestureListener extends GestureDetector.SimpleOnGestureListener {

        public CustomGestureListener() {
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2,
                float velocityX, float velocityY) {
            switchPlayerControllerDisplay();
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            switchPlayerControllerDisplay();
            return true;
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_ID_SET_ACTIONBAR_BACKGROUND:
                    APILevelWrapper api = APILevelWrapper.createInstance();
                    if (mOrientation == Configuration.ORIENTATION_PORTRAIT) {
                        if (mActionBarBackground != null && mActionBar != null) {
                            int height = api.getHeight_ActionBar(mActionBar);
                            if (api.isShowing_ActionBar(mActionBar) && height == 0) {
                                // 高さが取れないならもう一回やり直す
                                mHandler.sendEmptyMessageDelayed(
                                        MSG_ID_SET_ACTIONBAR_BACKGROUND, 50);
                            } else {
                                mActionBarBackground.getLayoutParams().height =
                                    height;
                                mActionBarBackground.requestLayout();
                            }
                        }
                    } else {
                        if (mActionBarBackground != null) {
                            mActionBarBackground.getLayoutParams().height = 0;
                            mActionBarBackground.requestLayout();
                        }
                    }
                    break;
            }
        }
    };

    public PlayerInfoControllerManager(Context context,
            PlayerInfoMiniLayout infoMini, ViewGroup controller,
            View actionBarBackground, ViewGroup playerInfoArea) {
        mWindowManager =
            (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        mInputMethodManager =
            (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        mPlayerInfoMini = infoMini;
        mPlayerController = controller;
        mActionBarBackground = actionBarBackground;
        mPlayerInfoArea = playerInfoArea;
        mGestureDetector = new GestureDetector(context,
                new CustomGestureListener());

        if (mPlayerInfoMini != null) {
            Resources res = context.getResources();
            mPlayerInfoMiniBackground = res.getDrawable(R.drawable.player_info_mini_background);

            mPlayerInfoMini.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switchPlayerInfoMiniDisplay();
                }
            });
            mPlayerInfoMini.setLayoutListener(new LayoutListener() {
                @Override
                public void onLayout(View view, int left, int top, int right, int bottom) {
                    if (mPlayerInfoArea != null) {
                        ViewGroup.MarginLayoutParams params =
                            (ViewGroup.MarginLayoutParams) mPlayerInfoArea.getLayoutParams();
                        int height = bottom - top;
                        if (params.bottomMargin != height) {
                            params.bottomMargin = height;
                            mPlayerInfoArea.requestLayout();
                        }
                    }
                }
            });
        }

        onOrientationChanged(context.getResources().getConfiguration().orientation);
    }

    public boolean onTouchEvent(MotionEvent event) {
//        APILevelWrapper api = APILevelWrapper.createInstance();
//        api.show_ActionBar(mActionBar);
        return mGestureDetector.onTouchEvent(event);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            if (!isPlayerControllerShown()) {
                showPlayerController();
//                return true;
            }
        }
        return false;
    }

    public boolean onBackPressed() {
        if (isPlayerControllerShown()) {
            hidePlayerController();
            return true;
        }
        return false;
    }

    public void switchPlayerControllerDisplay() {
        if (mPlayerController == null) {
            return;
        }
        if (isPlayerControllerShown()) {
            hidePlayerController();
        } else {
            showPlayerController();
        }
    }

    public boolean isPlayerControllerShown() {
        if (mPlayerController == null) {
            return false;
        }
        final int visibility = mPlayerController.getVisibility();
        if (visibility == View.VISIBLE
                && (mAnimControllerOut == null
                        || mPlayerController.getAnimation() != mAnimControllerOut)) {
            return true;
        } else {
            return false;
        }
    }
    public void showPlayerController() {
        if (mActionBar != null) {
            APILevelWrapper api = APILevelWrapper.createInstance();
            api.show_ActionBar(mActionBar);
        }

        if (mPlayerController != null) {
            if (mAnimControllerIn == null) {
                int controllerHeight = mPlayerController.getHeight();
                mAnimControllerIn = new TranslateAnimation(
                        0.0f, 0.0f, controllerHeight, 0.0f);
                mAnimControllerIn.setDuration(ANIM_TIME_PLAYER_CONTROLLER_IN);
                mAnimControllerIn.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationEnd(Animation animation) {
                        mPlayerController.clearAnimation();
                    }
                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }
                });
            }
            mPlayerController.setVisibility(View.VISIBLE);
            mPlayerController.startAnimation(mAnimControllerIn);

            if (mPlayerInfoMini != null) {
                showPlayerInfoMini();
                ViewGroup.LayoutParams params = mPlayerInfoMini.getLayoutParams();
                if (params instanceof ViewGroup.MarginLayoutParams) {
                    ((ViewGroup.MarginLayoutParams) params).bottomMargin =
                        mPlayerController.getHeight();
                }
                mPlayerInfoMini.requestLayout();
            }
        }

        if (mEventListener != null) {
            mEventListener.onPlayerControllerDisplayChanged(this, true);
        }
    }
    public void hidePlayerController() {
        if (mActionBar != null && mOrientation != Configuration.ORIENTATION_PORTRAIT) {
            APILevelWrapper api = APILevelWrapper.createInstance();
            api.hide_ActionBar(mActionBar);
        }

        if (mPlayerController != null) {
            if (isPlayerControllerShown()) {
                if (mAnimControllerOut == null) {
                    int controllerHeight = mPlayerController.getHeight();
                    mAnimControllerOut = new TranslateAnimation(
                            0.0f, 0.0f, 0.0f, controllerHeight);
                    mAnimControllerOut.setDuration(ANIM_TIME_PLAYER_CONTROLLER_OUT);
                    mAnimControllerOut.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationEnd(Animation animation) {
                            mPlayerController.setVisibility(View.INVISIBLE);
                            mPlayerController.clearAnimation();
                        }
                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }
                    });
                }
                mPlayerController.startAnimation(mAnimControllerOut);

                mInputMethodManager.hideSoftInputFromWindow(
                        mPlayerController.getWindowToken(), 0);
            }

            if (mPlayerInfoMini != null) {
                ViewGroup.LayoutParams params = mPlayerInfoMini.getLayoutParams();
                if (params instanceof ViewGroup.MarginLayoutParams) {
                    ((ViewGroup.MarginLayoutParams) params).bottomMargin = 0;
                }
                mPlayerInfoMini.requestLayout();
            }
        }

        if (mEventListener != null) {
            mEventListener.onPlayerControllerDisplayChanged(this, false);
        }
    }

    public void onOrientationChanged(int orientation) {
        mOrientation = orientation;
        DisplayMetrics metrics = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(metrics);
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            mTouchRangeWidth = ((float) (metrics.widthPixels * 2)) / 3.0f;
            mTouchRangeHeight = ((float) (metrics.heightPixels * 3)) / 4.0f;
        } else {
            mTouchRangeWidth = ((float) (metrics.widthPixels * 2)) / 3.0f;
            mTouchRangeHeight = ((float) (metrics.heightPixels * 2)) / 3.0f;
        }

        if (mActionBar != null) {
            APILevelWrapper api = APILevelWrapper.createInstance();
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                api.show_ActionBar(mActionBar);
            } else {
                if (!isPlayerControllerShown()) {
                    api.hide_ActionBar(mActionBar);
                }
            }
            // XXX 時間適当
            mHandler.sendEmptyMessageDelayed(MSG_ID_SET_ACTIONBAR_BACKGROUND, 50);
        }

        if (isPlayerInfoMiniShown()) {
            if (mOrientation == Configuration.ORIENTATION_PORTRAIT) {
                mPlayerInfoMini.setBackgroundDrawable(mPlayerInfoMiniBackground);
            } else {
                mPlayerInfoMini.setBackgroundDrawable(null);
            }
        }
    }

    public void setActionBar(Activity activity) {
        APILevelWrapper api = APILevelWrapper.createInstance();
        Object actionBar = api.getActionBar(activity);
        mActionBar = actionBar;

        if (actionBar == null) {
            return;
        }

        if (mOrientation == Configuration.ORIENTATION_PORTRAIT) {
            api.show_ActionBar(actionBar);
        } else {
            if (isPlayerControllerShown()) {
                api.show_ActionBar(actionBar);
            } else {
                api.hide_ActionBar(actionBar);
            }
        }
        // XXX 時間適当
        mHandler.sendEmptyMessageDelayed(MSG_ID_SET_ACTIONBAR_BACKGROUND, 50);

        if (mTitleCustomView == null) {
            api.setCustomView_ActionBar(actionBar, R.layout.player_title);
            mTitleCustomView = api.getCustomView_ActionBar(actionBar);
            if (mTitleCustomView != null) {
                mTitleCustomViewTitle = ViewUtil.findViewById(mTitleCustomView,
                        R.id.title_title);

                int actionBarHeight = mTitleCustomView.getLayoutParams().height;
                float titleSize = actionBarHeight * 0.7f;
//                mTitleCustomViewTitle.getLayoutParams().height =
//                    (int) titleSize;
                mTitleCustomViewTitle.setTextSize(titleSize * 0.7f);
                mTitleCustomViewTitle.setPadding(mTitleCustomViewTitle.getPaddingLeft(),
                        actionBarHeight / 10,
                        mTitleCustomViewTitle.getPaddingRight(),
                        mTitleCustomViewTitle.getPaddingBottom());

//                mTitleCustomView.requestLayout();
            }
        }
    }

    public void setTitle(String text) {
        if (mTitleCustomViewTitle != null) {
            mTitleCustomViewTitle.setText(text);
        }
    }

    public void switchPlayerInfoMiniDisplay() {
        if (mPlayerInfoMini == null) {
            return;
        }
        if (isPlayerInfoMiniShown()) {
            hidePlayerInfoMini();
        } else {
            showPlayerInfoMini();
        }
    }

    private boolean isPlayerInfoMiniShown() {
        if (mPlayerInfoMini == null) {
            return false;
        }
        // Clickできるようにするために子Viewのvisibilityを変更
        int count = mPlayerInfoMini.getChildCount();
        if (count == 0) {
            return false;
        }
        return (mPlayerInfoMini.getChildAt(0).getVisibility() == View.VISIBLE);
    }

    public void showPlayerInfoMini() {
        if (mPlayerInfoMini != null) {
            ViewUtil.setChildVisibility(mPlayerInfoMini, View.VISIBLE);
            if (mOrientation == Configuration.ORIENTATION_PORTRAIT) {
                mPlayerInfoMini.setBackgroundDrawable(mPlayerInfoMiniBackground);
            } else {
                mPlayerInfoMini.setBackgroundDrawable(null);
            }
        }
    }

    public void hidePlayerInfoMini() {
        if (mPlayerInfoMini != null) {
            ViewUtil.setChildVisibility(mPlayerInfoMini, View.INVISIBLE);
            mPlayerInfoMini.setBackgroundDrawable(null);
        }
    }

    public void setEventListener(EventListener listener) {
        mEventListener = listener;
    }
}
