package kr.co.hanwha.hifive.screen.task;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.adapter.TaskDetailListAdapter;
import kr.co.hanwha.hifive.adapter.TaskHistoryListAdapter;
import kr.co.hanwha.hifive.adapter.contract.TaskDetailListContract;
import kr.co.hanwha.hifive.base.BaseActivity;
import kr.co.hanwha.hifive.data.model.TaskDetailData;
import kr.co.hanwha.hifive.dialog.HFCalendarDialog;
import kr.co.hanwha.hifive.dialog.HFDefaultDialog;
import kr.co.hanwha.hifive.enums.BaseAnimationType;
import kr.co.hanwha.hifive.enums.BaseToolbarType;
import kr.co.hanwha.hifive.enums.EvaluationType;
import kr.co.hanwha.hifive.enums.TaskFlagType;
import kr.co.hanwha.hifive.screen.task.contract.TaskDetailContract;
import kr.co.hanwha.hifive.util.HFActivityUtil;
import kr.co.hanwha.hifive.util.HFCommonUtil;
import kr.co.hanwha.hifive.view.HFCommentEditView;
import kr.co.hanwha.hifive.view.HFEvaluationView;
import kr.co.hanwha.hifive.view.HFTaskPopupMenuView;

/**
 * TASK 상세 & 히스토리 View<br>
 *
 * @see TaskDetailPresenter
 * Created by sanghoonkwon on 2018. 2. 2..
 */

public class TaskDetailActivity extends BaseActivity implements TaskDetailContract.View {
    private ViewPager mViewPager;
    private View mViewDetail;
    private View mViewTransparent;

    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerViewTask;
    private HFCommentEditView mCommentEditView;
    private ImageButton mImageButtonHistory;
    private ImageButton mImageButtonMore;
    private ImageButton mImageButtonScrollToTop;
    private View mViewBottomMargin;
    private HFTaskPopupMenuView mTaskPopupMenuView;
    private HFEvaluationView mEvaluationView;

    private RecyclerView mRecyclerViewHistory;
    private TaskHistoryListAdapter mHistoryAdapter;

    private TaskDetailListAdapter mTaskAdapter;
    private TaskDetailContract.Presenter mPresenter;
    private boolean isVisibleEvaluation = false;
    private int mScreenHeight = 1920;
    private int mTaskId;
    private int mProjectId;
    private int mTrackId;
    private int mFlag = 0;

    private int mCurScrollY;

    @Override
    protected int getContentViewResource() {
        return R.layout.activity_task_detail;
    }

    @Override
    protected BaseToolbarType isToolbarStyle() {
        return null;
    }

    @Override
    protected BaseAnimationType isShowActivityAnimation() {
        return BaseAnimationType.RIGHT;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        mViewDetail = layoutInflater.inflate(R.layout.view_task_detail, null, false);
        mViewTransparent = layoutInflater.inflate(R.layout.view_task_transparent, null, false);

        // Initialize ViewPager
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        DetailPagerAdapter pagerAdapter = new DetailPagerAdapter();
        mViewPager.setAdapter(pagerAdapter);
        mViewPager.addOnPageChangeListener(onPageChangeListener);
        mViewPager.setOffscreenPageLimit(2);

        // Initialize History View
        mHistoryAdapter = new TaskHistoryListAdapter();
        mRecyclerViewHistory = (RecyclerView) findViewById(R.id.history_recyclerView);
        mRecyclerViewHistory.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerViewHistory.setAdapter(mHistoryAdapter);

        // Initialize History line
        int dp1 = HFCommonUtil.getPixelFromDimension(this, R.dimen.dimen_dp1);
        int dp10 = HFCommonUtil.getPixelFromDimension(this, R.dimen.dimen_dp10);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(dp1, ViewGroup.LayoutParams.MATCH_PARENT);
        params.addRule(RelativeLayout.CENTER_HORIZONTAL);
        params.topMargin = dp10;
        findViewById(R.id.line_view).setLayoutParams(params);

        // Initialize Detail
        mTaskAdapter = new TaskDetailListAdapter(this, onTaskDetailListener);

        mSwipeRefreshLayout = (SwipeRefreshLayout) mViewDetail.findViewById(R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setOnRefreshListener(onRefreshListener);

        mRecyclerViewTask = (RecyclerView) mViewDetail.findViewById(R.id.task_recyclerView);
        mRecyclerViewTask.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerViewTask.setAdapter(mTaskAdapter);
        mRecyclerViewTask.setItemAnimator(new DefaultItemAnimator());
        mRecyclerViewTask.addOnScrollListener(onScrollListener);

        mTaskPopupMenuView = (HFTaskPopupMenuView) mViewDetail.findViewById(R.id.taskPopupMenuView);
        mTaskPopupMenuView.setOnTaskPopupMenuListener(onTaskPopupMenuListener);

        mEvaluationView = (HFEvaluationView) mViewDetail.findViewById(R.id.evaluationView);
        mEvaluationView.setOnEvaluationListener(onEvaluationListener);

        mCommentEditView = (HFCommentEditView) mViewDetail.findViewById(R.id.commentEditView);
        mCommentEditView.setOnCommentEditListener(onCommentEditListener);

        mImageButtonHistory = (ImageButton) mViewDetail.findViewById(R.id.history_imageButton);
        mImageButtonMore = (ImageButton) mViewDetail.findViewById(R.id.more_imageButton);
        mImageButtonScrollToTop = (ImageButton) mViewDetail.findViewById(R.id.scrollToTop_imageButton);

        mImageButtonHistory.setOnClickListener(onClickListener);
        mImageButtonMore.setOnClickListener(onClickListener);
        mImageButtonScrollToTop.setOnClickListener(onClickListener);

        mViewBottomMargin = (View) mViewDetail.findViewById(R.id.bottomMargin_view);

        mViewDetail.findViewById(R.id.back_imageButton).setOnClickListener(onClickListener);

        mTaskId = getIntent().getIntExtra(HFActivityUtil.INTENT_TASK_ID, 0);
        mProjectId = getIntent().getIntExtra(HFActivityUtil.INTENT_PROJECT_ID, 0);
        mTrackId = getIntent().getIntExtra(HFActivityUtil.INTENT_TRACK_ID, 0);

        mTaskAdapter.setFlag(mFlag);
        mTaskAdapter.setActivity(this);

        mPresenter = new TaskDetailPresenter(this, mTaskAdapter, mTaskAdapter, mHistoryAdapter, mHistoryAdapter);
        mPresenter.initData(mTaskId, mProjectId, mTrackId, true);

        mScreenHeight = HFCommonUtil.getScreenHeight(this);
        mCurScrollY = 0;
    }

    @Override
    public void onBackPressed() {
        if (mViewPager.getCurrentItem() == 1)
            mViewPager.setCurrentItem(0, true);
        else
            super.onBackPressed();
    }

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

        mPresenter.detachView();
    }

    @Override
    public void setRefreshing(boolean refreshing) {
        mSwipeRefreshLayout.setRefreshing(refreshing);
    }

    @Override
    public void setLayout(@NonNull TaskDetailData data) {
        mFlag = data.getFlag();
        mTaskAdapter.setFlag(mFlag);
        mTaskPopupMenuView.setType(mFlag, data);

        if (TaskFlagType.NONE.getCode() == mFlag ||
                TaskFlagType.COMPLETED_MY_TASK.getCode() == mFlag) {
            findViewById(R.id.more_imageButton).setVisibility(View.GONE);
        } else if (TaskFlagType.ASSIGNED_MY_TASK.getCode() == mFlag ||
                TaskFlagType.WAITING_TO_ME.getCode() == mFlag ||
                TaskFlagType.REQUEST_TASK_REJECTED.getCode() == mFlag ||
                TaskFlagType.REQUEST_TASK_EVALUATION.getCode() == mFlag ||
                TaskFlagType.REQUEST_TASK_ASSIGNED.getCode() == mFlag) {
            findViewById(R.id.more_imageButton).setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == HFActivityUtil.EDIT_TASK && resultCode == RESULT_OK) {
            mPresenter.initData(mTaskId, mProjectId, mTrackId, true);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void scrollToTop() {
        mRecyclerViewTask.smoothScrollToPosition(0);
    }

    @Override
    public void scrollToBottom() {
        int position = mTaskAdapter.getItemCount() - 1;
        if (position >= 0)
            mRecyclerViewTask.smoothScrollToPosition(position);
    }

    @Override
    public void clearEditComment() {
        int height = HFCommonUtil.getPixelFromDimension(TaskDetailActivity.this, R.dimen.comment_min_height);
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
        mViewBottomMargin.setLayoutParams(param);

        mCommentEditView.requestFocus();
        mCommentEditView.clearText();
    }

    private void showFloatingMenu(int x, int y) {
        if (isVisibleEvaluation) return;
        isVisibleEvaluation = true;
        mEvaluationView.setVisibility(View.VISIBLE);
        mEvaluationView.showFloating(x, y);
//        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
    }

    private void hideFloatingMenu() {
        isVisibleEvaluation = false;
        mEvaluationView.setVisibility(View.GONE);
//        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
    }

    /**************************************************
     * CommentEditView.OnCommentEditListener
     **************************************************/
    HFCommentEditView.OnCommentEditListener onCommentEditListener = new HFCommentEditView.OnCommentEditListener() {
        @Override
        public void onFocusChange(@NonNull HFCommentEditView v, boolean b) {
            if (b) {
                v.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        scrollToBottom();//TODO - 한번만..
                    }
                }, 500);
            }
        }

        @Override
        public void onValueChanged(@NonNull HFCommentEditView v) {
        }

        @Override
        public void onAddCommentClicked(@NonNull HFCommentEditView v, @Nullable String contents) {
            mPresenter.doAddComment(v, contents);
        }

        @Override
        public void onHeightChanged(@NonNull int height) {
            //TODO - CHECK
//            height = -GWCommonUtil.getPixelFromDimension(TempTaskDetailActivity.this, R.dimen.common_size_12);
//            if (height < 0) height = 0;
//            LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
//            mViewBottomMargin.setLayoutParams(param);
        }
    };

    /**************************************************
     * HFEvaluationView.OnEvaluationListener
     **************************************************/
    HFEvaluationView.OnEvaluationListener onEvaluationListener = new HFEvaluationView.OnEvaluationListener() {
        @Override
        public void onDismiss() {
            hideFloatingMenu();
        }

        @Override
        public void onGreenClicked() {
            mPresenter.doEvaluation(EvaluationType.GREEN);
        }

        @Override
        public void onYellowClicked() {
            mPresenter.doEvaluation(EvaluationType.YELLOW);
        }

        @Override
        public void onRedClicked() {
            mPresenter.doEvaluation(EvaluationType.RED);
        }

        @Override
        public void onGrayClicked() {
            mPresenter.doEvaluation(EvaluationType.GRAY);
        }
    };
    /**************************************************
     * TaskPopupMenuView.OnTaskPopupMenuListener
     **************************************************/
    HFTaskPopupMenuView.OnTaskPopupMenuListener onTaskPopupMenuListener = new HFTaskPopupMenuView.OnTaskPopupMenuListener() {
        @Override
        public void dismiss() {
            Animation animFadeOut = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_out);
            animFadeOut.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    mTaskPopupMenuView.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
            mTaskPopupMenuView.startAnimation(animFadeOut);
        }

        @Override
        public void doEditTask() {
            mPresenter.doEditTask();
        }

        @Override
        public void doDeleteTask() {
            showAlert(getString(R.string.alert_default_title), getString(R.string.alert_delete_task), new HFDefaultDialog.OnDialogCallback() {
                @Override
                public void onNegative() {

                }

                @Override
                public void onPositive() {
                    mPresenter.doDeleteTask();
                }
            });
        }

        @Override
        public void doAccept() {
            mPresenter.doTaskAccept();
        }

        @Override
        public void doReject() {
            mPresenter.doTaskReject();
        }

        @Override
        public void doDeleteRequest() {
            mPresenter.doDeleteRequest();
        }

        @Override
        public void doReRequest() {
            mPresenter.doReRequest();
        }

        @Override
        public void doEvaluationConfirm() {
            mPresenter.doEvaluationConfirm();
        }

        @Override
        public void doEvaluationReject() {
            mPresenter.doEvaluationReject();
        }
    };

    /**************************************************
     * TaskDetailListContract.OnTaskDetailListener
     **************************************************/
    TaskDetailListContract.OnTaskDetailListener onTaskDetailListener = new TaskDetailListContract.OnTaskDetailListener() {
        @Override
        public void onUrlLinkClicked(String url) {
//            HFActivityUtil.startCommonWebViewActivity(TempTaskDetailActivity.this, url);
        }

        @Override
        public void onMessageMoreClicked() {
            mPresenter.moreMessageData();
        }

        @Override
        public void onTagClicked(@NonNull String tag) {
            HFActivityUtil.startSearchActivity(TaskDetailActivity.this, tag);
        }

        @Override
        public void onEvaluationClicked(int x, int y) {
            if (isVisibleEvaluation) hideFloatingMenu();
            else showFloatingMenu(x, y);
        }
    };

    /**************************************************
     * SwipeRefreshLayout.OnRefreshListener
     **************************************************/
    SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mPresenter.initData(mTaskId, mProjectId, mTrackId, false);
        }
    };

    /**************************************************
     * RecyclerView.OnScrollListener
     **************************************************/
    RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            mCurScrollY += dy;
            if (mCurScrollY < 0) mCurScrollY = 0;

            if (mCurScrollY > mScreenHeight) mImageButtonScrollToTop.setVisibility(View.VISIBLE);
            else mImageButtonScrollToTop.setVisibility(View.GONE);
        }


    };

    /**************************************************
     * View.OnClickListener
     **************************************************/
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.back_imageButton:
                    finish();
                    break;
                case R.id.history_imageButton:
                    mViewPager.setCurrentItem(1, true);
                    break;
                case R.id.more_imageButton:
                    mTaskPopupMenuView.setVisibility(View.VISIBLE);
                    Animation animFadeIn = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in);
                    mTaskPopupMenuView.startAnimation(animFadeIn);
                    break;
                case R.id.scrollToTop_imageButton:
                    scrollToTop();
                    break;
            }

        }
    };

    /**************************************************
     * ViewPager.OnPageChangeListener
     **************************************************/
    ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
//            mMainTabView.setCurrentItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    /**************************************************
     * PagerAdapter
     **************************************************/
    class DetailPagerAdapter extends PagerAdapter {
        @Override
        public float getPageWidth(int position) {
            if (position == 0) return 1.0f;
            else {
                float screenWidth = (float) HFCommonUtil.getScreenWidth(TaskDetailActivity.this);
                float margin = (float) HFCommonUtil.getPixelFromDimension(TaskDetailActivity.this, R.dimen.task_detail_history_margin);
                return (screenWidth - margin) / screenWidth;
            }
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (position == 0) {
                container.addView(mViewDetail);
                return mViewDetail;
            } else {
                container.addView(mViewTransparent);
                return mViewTransparent;
            }
        }
    }
}
