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

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.TextUtils;
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.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.base.BaseActivity;
import kr.co.hanwha.hifive.data.model.CampaignData;
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 mTextViewCancel;
    private TextView mTextViewRegister;

    private LinearLayout mLayoutHint;
    private TextView mTextViewHint;
    private EditText mEditText;
    private TextView mTextViewDueTo;
    private TextView mTextViewDueToToday;
    private HFReceiverContainerView mReceiverContainerView;

    private AddTaskContract.Presenter mPresenter;

    private boolean isEdit = false;
    private boolean isReRequest = 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);
        mTextViewCancel = (TextView) findViewById(R.id.cancel_textView);
        mTextViewRegister = (TextView) findViewById(R.id.register_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);

        mReceiverContainerView.setOnReceiverContainerListener(onReceiverContainerListener);

        mLayoutHint.setOnClickListener(onClickListener);
        findViewById(R.id.receiver_linearLayout).setOnClickListener(onClickListener);
        findViewById(R.id.dueTo_linearLayout).setOnClickListener(onClickListener);
        findViewById(R.id.campaign_linearLayout).setOnClickListener(onClickListener);
        mTextViewCancel.setOnClickListener(onClickListener);
        mTextViewRegister.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);
        isReRequest = getIntent().getBooleanExtra(HFActivityUtil.INTENT_IS_REREQUEST, false);
        if (isEdit) {
            int task_id = getIntent().getIntExtra(HFActivityUtil.INTENT_TASK_ID, 0);
            int project_id = getIntent().getIntExtra(HFActivityUtil.INTENT_PROJECT_ID, 0);
            mPresenter.initEditData(task_id, project_id);
        } else {
            mPresenter.initData();
        }
    }

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

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

    @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 setCampaignInfo(@Nullable CampaignData data) {
        TextView textViewCampaign = (TextView) findViewById(R.id.campaign_textView);
        TextView textViewCampaignHint = (TextView) findViewById(R.id.campaignHint_textView);
        ImageButton imageButtonClearCampaign = (ImageButton) findViewById(R.id.clearCampaign_imageButton);

        if (data != null && TextUtils.isEmpty(data.getCampaign_desc()) == false) {
            textViewCampaign.setText(data.getCampaign_desc());
            textViewCampaign.setVisibility(View.VISIBLE);
            textViewCampaignHint.setVisibility(View.GONE);
            imageButtonClearCampaign.setVisibility(View.VISIBLE);
            imageButtonClearCampaign.setOnClickListener(onClickListener);
        } else {
            textViewCampaign.setText("");
            textViewCampaign.setVisibility(View.GONE);
            textViewCampaignHint.setVisibility(View.VISIBLE);
            imageButtonClearCampaign.setVisibility(View.INVISIBLE);
            imageButtonClearCampaign.setOnClickListener(null);
        }
    }

    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.REQUEST_ADD_TASK_SELECT_MEMBER && resultCode == RESULT_OK) {
            setReceiverList(TaskDataRepository.getSelectedMemberList(), true);

            setCampaignInfo(TaskDataRepository.getSelectedCampaignData());

            if (isKeyboardStatus) showKeyboard();
        } else if (requestCode == HFActivityUtil.REQUEST_ADD_TASK_SELECT_CAMPAIGN && resultCode == RESULT_OK) {
            setCampaignInfo(TaskDataRepository.getSelectedCampaignData());

            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.register_textView:
                    if (isEdit) {
                        mPresenter.updateTask(mEditText.getText().toString(), isReRequest);
                    } else {
                        mPresenter.requestSendTask(mEditText.getText().toString());
                    }
                    break;
                case R.id.cancel_textView:
                    finish();
                    break;
                case R.id.receiver_linearLayout: {
                    if (isEdit) return;//수정모드일땐 사람 변경 X

                    isKeyboardStatus = isKeyboardShow;
                    HFActivityUtil.startAddTaskSelectMemberActivity(AddTaskActivity.this);
                    break;
                }
                case R.id.dueTo_linearLayout:
                    mPresenter.showCalendarDialog();
                    break;
                case R.id.campaign_linearLayout: {
                    isKeyboardStatus = isKeyboardShow;
                    HFActivityUtil.startAddTaskSelectCampaignActivity(AddTaskActivity.this);
                    break;
                }
                case R.id.clearCampaign_imageButton:
                    TaskDataRepository.clearSelectedCampaignData();
                    setCampaignInfo(null);
                    break;
                case R.id.hint_lienarLayout:
                    showKeyboard();
                    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);
        }
    };

    /**************************************************
     * 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) {
            String text = s.toString();
            if (text.length() == 0) {
                mLayoutHint.setVisibility(View.VISIBLE);
            } else {
                mLayoutHint.setVisibility(View.GONE);
            }

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