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

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;

import java.util.ArrayList;
import java.util.Collections;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.adapter.contract.TaskDetailListContract;
import kr.co.hanwha.hifive.adapter.contract.TaskHistoryListContract;
import kr.co.hanwha.hifive.data.model.BaseData;
import kr.co.hanwha.hifive.data.model.MessageAddData;
import kr.co.hanwha.hifive.data.model.MessageListData;
import kr.co.hanwha.hifive.data.model.MessageListRoot;
import kr.co.hanwha.hifive.data.model.TaskDetailData;
import kr.co.hanwha.hifive.data.model.TaskDetailRoot;
import kr.co.hanwha.hifive.data.model.TaskHistoryData;
import kr.co.hanwha.hifive.data.source.AlarmDataRepository;
import kr.co.hanwha.hifive.data.source.TaskDataRepository;
import kr.co.hanwha.hifive.dialog.HFDefaultDialog;
import kr.co.hanwha.hifive.dialog.HFEvaluationDialog;
import kr.co.hanwha.hifive.dialog.HFTaskInputDialog;
import kr.co.hanwha.hifive.enums.TaskEvaluationType;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkCallback;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkError;
import kr.co.hanwha.hifive.screen.task.contract.TaskDetailContract;
import kr.co.hanwha.hifive.util.HFActivityUtil;
import kr.co.hanwha.hifive.util.HFInfoUtil;
import kr.co.hanwha.hifive.view.HFCommentEditView;

/**
 * TASK 상세 & 히스토리 Presenter<br>
 *
 * @see TaskDetailActivity
 * Created by sanghoonkwon on 2018. 1. 22..
 */

public class TaskDetailPresenter implements TaskDetailContract.Presenter {
    private TaskDetailContract.View mView;
    private TaskDetailListContract.View mAdapterView;
    private TaskDetailListContract.Model mAdapterModel;
    private TaskHistoryListContract.View mAdapterViewHistory;
    private TaskHistoryListContract.Model mAdapterModelHistory;

    private TaskDetailRoot mRoot;
    private TaskDetailData mData;
    private int mCurrentPage = 1;
    private int mTotalCount = 0;

    public TaskDetailPresenter(@NonNull TaskDetailContract.View view,
                               @NonNull TaskDetailListContract.View adapterView,
                               @NonNull TaskDetailListContract.Model adapterModel,
                               @NonNull TaskHistoryListContract.View adapterViewHistory,
                               @NonNull TaskHistoryListContract.Model adapterModelHistory) {
        mView = view;
        mAdapterView = adapterView;
        mAdapterModel = adapterModel;
        mAdapterViewHistory = adapterViewHistory;
        mAdapterModelHistory = adapterModelHistory;
    }

    @Override
    public void detachView() {
        mView = null;

    }

    @Override
    public Context getContext() {
        return (Context) mView;
    }

    @Override
    public void checkNotificationOpen(@NonNull int task_id, @NonNull int project_id) {
        AlarmDataRepository.getInstance().requestNotificationOpen(getContext(), 0, task_id, project_id, 0, null);
    }

    @Override
    public void initData(@NonNull final int task_id, @NonNull final int project_id, final boolean needLoading) {
        TaskDataRepository.getInstance().requestGetTaskDetail(getContext(), task_id, project_id,
                new HanwhaNetworkCallback<TaskDetailRoot>() {
                    @Override
                    public void onSuccess(TaskDetailRoot response) {

                        mRoot = response;
                        if (response != null)
                            mData = response.getTaskResult();

                        if (mView != null)
                            mView.setLayout(mData);

                        mAdapterModel.setTaskItem(mRoot);
                        mAdapterView.notifyDataAll();

                        initHistoryData(response.getListTasksHistory());

                        initMessageData(false, needLoading);
                    }

                    @Override
                    public void onFailure(HanwhaNetworkError error) {
                        mView.showAlert(error, new HFDefaultDialog.OnDialogCallback() {
                            @Override
                            public void onNegative() {
                                getActivity().finish();
                            }

                            @Override
                            public void onPositive() {
                                initData(task_id, project_id, needLoading);
                            }
                        });
                        mView.showLoadingDialog(false);
                        mView.setRefreshing(false);
                    }

                    @Override
                    public void onPreExecute() {
                        if (needLoading)
                            mView.showLoadingDialog(true);
                    }

                    @Override
                    public void onPostExecute() {
//                        mView.showLoadingDialog(false);
//                        mView.setRefreshing(false);
                    }
                });
    }

    @Override
    public void initHistoryData(ArrayList<TaskHistoryData> list) {
        mAdapterModelHistory.addItems(list);
        mAdapterViewHistory.notifyDataAll();
    }

    @Override
    public void initMessageData(final boolean needScrollBottom, final boolean needLoading) {
        mCurrentPage = 1;
        TaskDataRepository.getInstance().requestGetMessageList(getContext(), mData.getTask_id(), mCurrentPage, new HanwhaNetworkCallback<MessageListRoot>() {
            @Override
            public void onSuccess(MessageListRoot response) {
                if (response != null) {
                    mTotalCount = response.getCountOfTotalRecords();
                    mAdapterModel.setTotalCount(mTotalCount);
                    ArrayList<MessageListData> list = response.getListRequestMessagesResult();
//                    if (list != null) Collections.reverse(list);

                    mAdapterModel.clearItems();
                    mAdapterModel.addItems(list);
                }
                mAdapterView.notifyDataAllWithoutHeader();

                if (needScrollBottom) mView.scrollToBottom();
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                mView.showLoadingDialog(false);
                mView.setRefreshing(false);
            }

            @Override
            public void onPreExecute() {
                if (needLoading)
                    mView.showLoadingDialog(true);
            }

            @Override
            public void onPostExecute() {
                mView.showLoadingDialog(false);
                mView.setRefreshing(false);
            }
        });
    }


    @Override
    public void moreMessageData() {
        mCurrentPage += 1;
        TaskDataRepository.getInstance().requestGetMessageList(getContext(), mData.getTask_id(), mCurrentPage, new HanwhaNetworkCallback<MessageListRoot>() {
            @Override
            public void onSuccess(MessageListRoot response) {
                if (response != null) {
                    mTotalCount = response.getCountOfTotalRecords();
                    mAdapterModel.setTotalCount(mTotalCount);
                    ArrayList<MessageListData> list = response.getListRequestMessagesResult();
                    if (list != null) Collections.reverse(list);

                    mAdapterModel.addItems(list);
                }
                mAdapterView.notifyDataAll();
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                mView.showAlert(error);
            }

            @Override
            public void onPreExecute() {
                mView.showLoadingDialog(true);
            }

            @Override
            public void onPostExecute() {
                mView.showLoadingDialog(false);
                mView.setRefreshing(false);
            }
        });
    }

    @Override
    public void refreshData() {
        initData(mData.getTask_id(), mData.getProject_id(), true);
    }

    @Override
    public void doEditTask() {
        HFActivityUtil.startEditTaskActivity(getActivity(), mData.getTask_id(), mData.getProject_id());
    }

    @Override
    public void doDeleteTask() {
        TaskDataRepository.getInstance().requestDeleteTask(getContext(), mData, new HanwhaNetworkCallback() {
            @Override
            public void onSuccess(Object response) {
                HFInfoUtil.setNeedRefreshMainHomeListRequest(getContext());
                HFInfoUtil.setNeedRefreshMainProjectList(getContext());//TODO - CHECK refresh
                mView.showToastConfirm(R.string.alert_task_deleted);
                getActivity().setResult(Activity.RESULT_OK);
                getActivity().finish();
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                mView.showAlert(error);
            }

            @Override
            public void onPreExecute() {
                mView.showLoadingDialog(true);
            }

            @Override
            public void onPostExecute() {
                mView.showLoadingDialog(false);
            }
        });
    }

    @Override
    public void doTaskAccept() {
        TaskDataRepository.getInstance().requestTaskAccept(getContext(), mData, refreshHanwhaNetworkCallback);
    }

    @Override
    public void doTaskReject() {
        new HFTaskInputDialog(getActivity(), R.string.task_reject_title, new HFTaskInputDialog.OnDialogCallback() {
            @Override
            public void onPositive(@NonNull final String message) {
                TaskDataRepository.getInstance().requestTaskReject(getContext(),
                        mData, message, refreshHanwhaNetworkCallback);
            }
        }).show();
    }

    @Override
    public void showEvaluationDialog() {
        new HFEvaluationDialog(getActivity(), new HFEvaluationDialog.OnDialogCallback() {
            @Override
            public void onPositive(@NonNull TaskEvaluationType type) {
                doEvaluation(type);
            }
        }).show();
    }

    @Override
    public void doEvaluation(@NonNull TaskEvaluationType taskEvaluationType) {
        TaskDataRepository.getInstance().requestSetTaskEvaluation(getContext(), mData, taskEvaluationType,
                new HanwhaNetworkCallback<BaseData>() {
                    @Override
                    public void onSuccess(BaseData response) {
                        refreshData();
                        HFInfoUtil.setNeedRefreshMainHomeListAssigned(getContext());
                        HFInfoUtil.setNeedRefreshMainProjectList(getContext());//TODO - CHECK
                    }

                    @Override
                    public void onFailure(HanwhaNetworkError error) {
                        mView.showAlert(error);
                    }

                    @Override
                    public void onPreExecute() {
                        mView.showLoadingDialog(true);
                    }

                    @Override
                    public void onPostExecute() {
                        mView.showLoadingDialog(false);
                    }
                });
    }

    @Override
    public void doEvalAcceptClicked() {
        TaskDataRepository.getInstance().requestSetTaskEvaluationAccept(getContext(), mData, refreshHanwhaNetworkCallback);
    }

    @Override
    public void doEvalRejectClicked() {
        new HFTaskInputDialog(getActivity(), R.string.task_eval_reject_title, new HFTaskInputDialog.OnDialogCallback() {
            @Override
            public void onPositive(@NonNull final String message) {
                TaskDataRepository.getInstance().requestSetTaskEvaluationReject(getContext(),
                        mData, message, refreshHanwhaNetworkCallback);
            }
        }).show();
    }

    @Override
    public void doDeleteRequestClicked() {
        TaskDataRepository.getInstance().requestSetTaskDeleteRequest(getContext(), mData, new HanwhaNetworkCallback() {
            @Override
            public void onSuccess(Object response) {
                HFInfoUtil.setNeedRefreshMainHomeListRequest(getContext());
                HFInfoUtil.setNeedRefreshMainProjectList(getContext());//TODO - CHECK
                mView.showToastConfirm(R.string.alert_task_canceled);
                getActivity().setResult(Activity.RESULT_OK);
                getActivity().finish();
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                mView.showAlert(error);
            }

            @Override
            public void onPreExecute() {
                mView.showLoadingDialog(true);
            }

            @Override
            public void onPostExecute() {
                mView.showLoadingDialog(false);
            }
        });
    }

    @Override
    public void doReRequestClicked() {
        HFActivityUtil.startEditTaskAndReRequestActivity(getActivity(), mData.getTask_id(), mData.getProject_id());
    }

    @Override
    public void doAddComment(@NonNull final HFCommentEditView commentEditView, @NonNull String contents) {
        TaskDataRepository.getInstance().requestAddMessage(getContext(), mData.getTask_id(), contents, new HanwhaNetworkCallback<MessageAddData>() {
            @Override
            public void onSuccess(MessageAddData response) {
                mView.clearEditComment();

                initMessageData(true, true);
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                mView.showAlert(error);
            }

            @Override
            public void onPreExecute() {
                mView.showLoadingDialog(true);
            }

            @Override
            public void onPostExecute() {
                mView.showLoadingDialog(false);
            }
        });
    }

    @Override
    public void doDeleteComment(int id) {
        TaskDataRepository.getInstance().requestDeleteMessage(getContext(), id, new HanwhaNetworkCallback() {
            @Override
            public void onSuccess(Object response) {
                initMessageData(true, true);
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                mView.showAlert(error);
            }

            @Override
            public void onPreExecute() {
                mView.showLoadingDialog(true);
            }

            @Override
            public void onPostExecute() {
                mView.showLoadingDialog(false);
            }
        });
    }

    /**************************************************
     * HanwhaNetworkCallback
     **************************************************/
    HanwhaNetworkCallback refreshHanwhaNetworkCallback = new HanwhaNetworkCallback() {
        @Override
        public void onSuccess(Object response) {
            HFInfoUtil.setNeedRefreshMainHomeListRequest(getContext());
            HFInfoUtil.setNeedRefreshMainProjectList(getContext());//TODO - CHECK
            mView.showToastConfirm(R.string.alert_completed);
            getActivity().setResult(Activity.RESULT_OK);
            refreshData();
        }

        @Override
        public void onFailure(HanwhaNetworkError error) {
            mView.showAlert(error);
        }

        @Override
        public void onPreExecute() {
            mView.showLoadingDialog(true);
        }

        @Override
        public void onPostExecute() {
            mView.showLoadingDialog(false);
        }
    };

    /**************************************************
     * Support methods
     **************************************************/
    private Activity getActivity() {
        return (Activity) mView;
    }
}
