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

import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.base.BaseActivity;
import kr.co.hanwha.hifive.data.model.MemberInfoData;
import kr.co.hanwha.hifive.data.model.TaskData;
import kr.co.hanwha.hifive.data.source.MemberDataRepository;
import kr.co.hanwha.hifive.data.source.TaskDataRepository;
import kr.co.hanwha.hifive.enums.BaseAnimationType;
import kr.co.hanwha.hifive.enums.BaseToolbarType;
import kr.co.hanwha.hifive.screen.task.contract.AddTaskContract;
import kr.co.hanwha.hifive.util.HFActivityUtil;
import kr.co.hanwha.hifive.util.HFDateUtil;
import kr.co.hanwha.hifive.util.HFSpanUtil;
import kr.co.hanwha.hifive.view.HFReceiverContainerView;

/**
 * Add Task : View
 *
 * @see AddTaskPresenter
 * Created by sanghoonkwon on 2018. 1. 17..
 */

public class AddTaskActivity extends BaseActivity implements AddTaskContract.View {
    private View mViewBackground;
    private TextView mTextViewActionCompleted;
    private TextView mTextViewActionRegister;
    private TextView mTextViewActionRequest;
    private LinearLayout mLayoutHint;
    private TextView mTextViewHint;
    private EditText mEditText;
    private TextView mTextViewDueTo;
    private TextView mTextViewDueToToday;
    private HFReceiverContainerView mReceiverContainerView;
    private LinearLayout mLayoutArrow;

    private AddTaskContract.Presenter mPresenter;

    private boolean isEdit = false;
    private boolean isRequest = false;
    private boolean isKeyboardShow = false;
    private boolean isKeyboardStatus = false;

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

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

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

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

        mViewBackground = (View) findViewById(R.id.background_view);
        mTextViewActionCompleted = (TextView) findViewById(R.id.actionCompleted_textView);
        mTextViewActionRegister = (TextView) findViewById(R.id.actionRegister_textView);
        mTextViewActionRequest = (TextView) findViewById(R.id.actionRequest_textView);
        mLayoutHint = (LinearLayout) findViewById(R.id.hint_lienarLayout);
        mTextViewHint = (TextView) findViewById(R.id.hint_textView);
        mEditText = (EditText) findViewById(R.id.editText);
        mEditText.addTextChangedListener(textWatcher);
        mTextViewDueTo = (TextView) findViewById(R.id.dueTo_textView);
        mTextViewDueToToday = (TextView) findViewById(R.id.dueToToday_textView);
        mReceiverContainerView = (HFReceiverContainerView) findViewById(R.id.receiverContainerView);
        mLayoutArrow = (LinearLayout) findViewById(R.id.arrow_linearLayout);

        mReceiverContainerView.setOnReceiverContainerListener(onReceiverContainerListener);
        mTextViewActionCompleted.setOnClickListener(onClickListener);
        findViewById(R.id.action_relativeLayout).setOnClickListener(onClickListener);
        mLayoutHint.setOnClickListener(onClickListener);
        findViewById(R.id.dueTo_linearLayout).setOnClickListener(onClickListener);
        mLayoutArrow.setOnClickListener(onClickListener);
        findViewById(R.id.close_imageButton).setOnClickListener(onClickListener);

        RelativeLayout layoutContainer = (RelativeLayout) findViewById(R.id.container_relativeLayout);
        layoutContainer.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);

        mTextViewHint.setText(String.format(getString(R.string.add_task_name_hint), MemberDataRepository.getInstance().getMemberName()));
        showKeyboard();

        startBlinkingAnimation();

        mPresenter = new AddTaskPresenter(this);
        isEdit = getIntent().getBooleanExtra(HFActivityUtil.INTENT_IS_EDIT, false);
        if (isEdit) {
            mTextViewActionCompleted.setVisibility(View.VISIBLE);
            findViewById(R.id.action_relativeLayout).setVisibility(View.GONE);
            mPresenter.initEditData();
        } else {
            mTextViewActionCompleted.setVisibility(View.GONE);
            findViewById(R.id.action_relativeLayout).setVisibility(View.VISIBLE);
            mPresenter.initData();
        }


//        mViewBackground.setAlpha(1.0f);
//        final Animation anim = new AlphaAnimation(1.0f, 0.0f);
//        anim.setDuration(200);
//        mViewBackground.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                mViewBackground.startAnimation(anim);
//            }
//        }, 100);

    }

    @Override
    public void setTaskData(@NonNull TaskData taskData) {
        mEditText.setText(taskData.getDescription());
        setDuedate(taskData.getDue_to());
        checkActionButton();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
    }

    private void startBlinkingAnimation() {
        View viewHintCursor = findViewById(R.id.hintCursor_view);
        Animation anim = new AlphaAnimation(0.0f, 1.0f);
        anim.setDuration(500);
        anim.setStartOffset(20);
        anim.setRepeatMode(Animation.REVERSE);
        anim.setRepeatCount(Animation.INFINITE);
        viewHintCursor.startAnimation(anim);
    }

    private void showRequestButton() {
        AnimatorSet setOut = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.flip_right_out);
        AnimatorSet setIn = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.flip_left_in);

        setOut.setTarget(mTextViewActionRegister);
        setIn.setTarget(mTextViewActionRequest);
        setOut.start();
        setIn.start();
    }

    private void showRegisterButton() {
        AnimatorSet setOut = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.flip_right_out);
        AnimatorSet setIn = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.flip_left_in);

        setOut.setTarget(mTextViewActionRequest);
        setIn.setTarget(mTextViewActionRegister);
        setOut.start();
        setIn.start();
    }

    @Override
    public void setDuedate(String selectedDate) {
        mTextViewDueTo.setText(selectedDate);
        String today = HFDateUtil.getDateFormatToday(HFDateUtil.FORMAT_TASK_ADD_DUEDATE_SERVER);
        mTextViewDueToToday.setVisibility(today.equals(selectedDate) ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setReceiverList(@Nullable ArrayList<MemberInfoData> list, @NonNull boolean isEditable) {
        mReceiverContainerView.setMemberList(list);
        mReceiverContainerView.setEdtiable(isEditable);
    }

    @Override
    public void checkActionButton() {
        if (isEdit) {
            mTextViewActionCompleted.setEnabled(mEditText.getText().toString().length() > 0);
        } else {
            if (mPresenter.isMyTask()) {
                mTextViewActionRegister.setEnabled(mEditText.getText().toString().length() > 0);
            } else {
                mTextViewActionRequest.setEnabled(mEditText.getText().toString().length() > 0);
            }

            if (isRequest != mPresenter.isRequest()) {
                isRequest = mPresenter.isRequest();
                if (isRequest)
                    showRequestButton();
                else
                    showRegisterButton();
            }
        }
    }

    private void showKeyboard() {
        mEditText.requestFocus();
        mEditText.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager input = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                input.showSoftInput(mEditText, InputMethodManager.SHOW_IMPLICIT);
            }
        }, 100);
    }

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

        if (isKeyboardStatus) showKeyboard();
    }

    /**************************************************
     * onActivityResult
     **************************************************/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == HFActivityUtil.ADD_TASK_SELECT_MEMBER && resultCode == RESULT_OK) {
            checkActionButton();

            setReceiverList(TaskDataRepository.getSelectedDataList(), true);

            if (isKeyboardStatus) showKeyboard();
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**************************************************
     * View.OnClickListener
     **************************************************/
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.action_relativeLayout:
                    mPresenter.requestSendTask(mEditText.getText().toString());
                    break;
                case R.id.actionCompleted_textView:
                    mPresenter.updateTask(mEditText.getText().toString());
                    break;
                case R.id.dueTo_linearLayout:
                    mPresenter.showCalendarDialog();
                    break;
                case R.id.hint_lienarLayout:
                    showKeyboard();
                    break;
                case R.id.arrow_linearLayout:
                    ((InputMethodManager) mEditText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
                    break;
                case R.id.close_imageButton:
                    finish();
                    break;
            }
        }
    };

    /**************************************************
     * ViewTreeObserver.OnGlobalLayoutListener
     **************************************************/
    ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            RelativeLayout layoutContainer = (RelativeLayout) findViewById(R.id.container_relativeLayout);
            if ((layoutContainer.getRootView().getHeight() - layoutContainer.getHeight()) >
                    layoutContainer.getRootView().getHeight() / 3) {
                isKeyboardShow = true;
            } else {
                isKeyboardShow = false;
            }
        }
    };

    /**************************************************
     * HFReceiverContainerView.OnReceiverContainerListener
     **************************************************/
    HFReceiverContainerView.OnReceiverContainerListener onReceiverContainerListener = new HFReceiverContainerView.OnReceiverContainerListener() {
        @Override
        public void onAddMemberClicked() {
            isKeyboardStatus = isKeyboardShow;
            HFActivityUtil.startAddTaskSelectMemberActivity(AddTaskActivity.this);
        }

        @Override
        public void onWriteToMeClicked() {
            checkActionButton();
        }
    };

    /**************************************************
     * EditText - TextWatcher
     **************************************************/
    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            checkActionButton();

            String text = s.toString();
            if (text.length() == 0) {
                mLayoutHint.setVisibility(View.VISIBLE);
            } else {
                mLayoutHint.setVisibility(View.GONE);
            }

            HFSpanUtil.getTagListSetColorSpan(AddTaskActivity.this, s);
        }
    };
}
