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 java.lang.reflect.Member;

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.MessageListData;
import kr.co.hanwha.hifive.data.model.TaskDetailData;
import kr.co.hanwha.hifive.data.source.MemberDataRepository;
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.TaskFlagType;
import kr.co.hanwha.hifive.enums.TaskStatusType;
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.CustomViewPager;
import kr.co.hanwha.hifive.view.HFCommentEditView;
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 CustomViewPager mViewPager;
    private View mViewDetail;
    private View mViewHistory;

    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 View mViewCover;

    private RecyclerView mRecyclerViewHistory;
    private TaskHistoryListAdapter mHistoryAdapter;

    private TaskDetailListAdapter mTaskAdapter;
    private TaskDetailContract.Presenter mPresenter;
    private int mScreenHeight = 1920;
    private int mTaskId;
    private int mProjectId;
    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);
        mViewHistory = layoutInflater.inflate(R.layout.view_task_history, null, false);

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

        // 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);

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

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

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

        mViewDetail.findViewById(R.id.back_imageButton).setOnClickListener(onClickListener);
        mViewCover = (View) mViewDetail.findViewById(R.id.coverView);

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

        mTaskAdapter.setFlag(mFlag);

        // Initialize History View
        mHistoryAdapter = new TaskHistoryListAdapter();
        mRecyclerViewHistory = (RecyclerView) mViewHistory.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;
        mViewHistory.findViewById(R.id.line_view).setLayoutParams(params);

        // Initialize Data
        mTaskId = getIntent().getIntExtra(HFActivityUtil.INTENT_TASK_ID, 0);
        mProjectId = getIntent().getIntExtra(HFActivityUtil.INTENT_PROJECT_ID, 0);
        mPresenter = new TaskDetailPresenter(this, mTaskAdapter, mTaskAdapter, mHistoryAdapter, mHistoryAdapter);
        mPresenter.initData(mTaskId, mProjectId, true);

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

        mPresenter.checkNotificationOpen(mTaskId, mProjectId);// TODO - CHECK
    }

    @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);

        boolean isAuthor = MemberDataRepository.getInstance().isMember(data.getAuthor_member_id());
        boolean isReceiver = MemberDataRepository.getInstance().isMember(data.getMember_id());
        boolean isVisible = false;
        if (TaskStatusType.ASSIGNED.getCode() == data.getStatus() && isReceiver) {
            isVisible = true;
        } else if (TaskStatusType.REQUESTED.getCode() == data.getStatus()) {
            isVisible = true;
        } else if (TaskStatusType.REJECTED_REQUEST.getCode() == data.getStatus() && isAuthor) {
            isVisible = true;
        } else if (TaskStatusType.DOING_TODAY.getCode() == data.getStatus() && isReceiver) {
            isVisible = true;
        } else if (TaskStatusType.EVALUATED.getCode() == data.getStatus() && isAuthor) {
            isVisible = true;
        } else if (TaskStatusType.CLOSED.getCode() == data.getStatus()) {
            isVisible = false;
        } else {
            isVisible = false;
        }
        mImageButtonMore.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == HFActivityUtil.REQUEST_EDIT_TASK && resultCode == RESULT_OK) {
            mPresenter.initData(mTaskId, mProjectId, true);
        } else if (requestCode == HFActivityUtil.REQUEST_EDIT_TASK_REREQUEST && resultCode == RESULT_OK) {
            mPresenter.initData(mTaskId, mProjectId, 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();
    }

    /**************************************************
     * 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();
                    }
                }, 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);
        }
    };

    /**************************************************
     * 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.doDeleteRequestClicked();
        }

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

        @Override
        public void doEvaluationAccept() {
            mPresenter.doEvalAcceptClicked();
        }

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

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

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

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

        @Override
        public void onEvaluationClicked() {
            mPresenter.showEvaluationDialog();
        }

        @Override
        public void onDeleteCommentClicked(final MessageListData data) {
            showAlert(getString(R.string.alert_default_title),
                    getString(R.string.alert_delete_task),
                    getString(R.string.alert_cancel),
                    getString(R.string.alert_delete),
                    new HFDefaultDialog.OnDialogCallback() {
                        @Override
                        public void onNegative() {

                        }

                        @Override
                        public void onPositive() {
                            mPresenter.doDeleteComment(data.getId());
                        }
                    });

        }
    };

    /**************************************************
     * SwipeRefreshLayout.OnRefreshListener
     **************************************************/
    SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mPresenter.initData(mTaskId, mProjectId, 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;
                case R.id.coverView:
                    if (mViewPager.getCurrentItem() == 1)
                        mViewPager.setCurrentItem(0, true);
                    break;
            }

        }
    };

    /**************************************************
     * ViewPager.PageTransformer
     **************************************************/
    public class DepthPageTransformer implements ViewPager.PageTransformer {
        private static final float MIN_SCALE = 1f;//0.75f

        public void transformPage(View view, float position) {
            int pageWidth = view.getWidth();

            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);
            } else if (position <= 0) { // [-1,0]
                // Use the default slide transition when moving to the left page
                view.setAlpha(1);
                view.setTranslationX(0);
                view.setScaleX(1);
                view.setScaleY(1);

            } else if (position <= 1) { // (0,1]
                // Fade the page out.
                view.setAlpha(1 - position);

                // Counteract the default slide transition
                view.setTranslationX(pageWidth * -position);

                // Scale the page down (between MIN_SCALE and 1)
                float scaleFactor = MIN_SCALE
                        + (1 - MIN_SCALE) * (1 - Math.abs(position));
                view.setScaleX(scaleFactor);
                view.setScaleY(scaleFactor);

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
            }
        }
    }

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

        }

        @Override
        public void onPageSelected(int position) {
            mViewCover.setVisibility(position == 0 ? View.GONE : View.VISIBLE);
        }

        @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(mViewHistory);
                return mViewHistory;
            }
        }
    }
}
