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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.util.ArrayList;

import kr.co.hanwha.hifive.BuildConfig;
import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.data.model.LoginData;
import kr.co.hanwha.hifive.data.model.NoticeData;
import kr.co.hanwha.hifive.data.model.NotificationData;
import kr.co.hanwha.hifive.data.model.UpdateData;
import kr.co.hanwha.hifive.data.source.MemberDataRepository;
import kr.co.hanwha.hifive.dialog.HFDefaultDialog;
import kr.co.hanwha.hifive.dialog.HFPickerDialog;
import kr.co.hanwha.hifive.dialog.HFSingleDialog;
import kr.co.hanwha.hifive.network.HFNetworkUtil;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkCallback;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkError;
import kr.co.hanwha.hifive.screen.intro.contract.IntroContract;
import kr.co.hanwha.hifive.util.HFActivityUtil;
import kr.co.hanwha.hifive.util.HFCommonUtil;
import kr.co.hanwha.hifive.util.HFInfoUtil;
import kr.co.hanwha.hifive.util.HFNotiUtil;

/**
 * SPLASH, 아이디 로그인, 간편 로그인 Presenter
 *
 * @see IntroActivity
 * Created by sanghoonkwon on 2018. 1. 11..
 */

public class IntroPresenter implements IntroContract.Presenter {
    private IntroContract.View mView;

    public IntroPresenter(@NonNull IntroContract.View view) {
        mView = view;
    }

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

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

    @Override
    public void checkLanding(Intent intent) {
        if (intent == null) return;

        String group_id = intent.getStringExtra(HFNotiUtil.KEY_GROUP_ID);
        String title = intent.getStringExtra(HFNotiUtil.KEY_TITLE);
        String message = intent.getStringExtra(HFNotiUtil.KEY_MESSAGE);
        String type = intent.getStringExtra(HFNotiUtil.KEY_TYPE);
        String value1 = intent.getStringExtra(HFNotiUtil.KEY_VALUE1);
        String value2 = intent.getStringExtra(HFNotiUtil.KEY_VALUE2);
        String value3 = intent.getStringExtra(HFNotiUtil.KEY_VALUE3);
        String db_code = intent.getStringExtra(HFNotiUtil.KEY_DB_CODE);

        NotificationData notificationData = new NotificationData(group_id, title, message, type, value1, value2, value3, db_code);
        HFNotiUtil.setNotificationData(getContext(), notificationData);
    }

    @Override
    public void checkUpdate() {
        String login_id = HFInfoUtil.getMemberLoginId(getContext());
        HFNetworkUtil networkUtil = new HFNetworkUtil();
        networkUtil.requestCheckUpdate(getContext(), login_id, new HanwhaNetworkCallback<UpdateData>() {
            @Override
            public void onSuccess(final UpdateData response) {
                MemberDataRepository.setUpdateData(response);

                if (HFCommonUtil.checkUpdate(getContext(), response) == false) {
                    NoticeData notice = checkNotice(response);
                    HFInfoUtil.setNoticeData(getContext(), notice);

                    if (response != null && response.isSimpleLoginYn()) {
                        mView.showSimpleLogin();
                    } else {
                        mView.showAccountLogin();
                    }
                } else {
                    String title = getContext().getString(R.string.app_name);
                    String message = getContext().getString(R.string.alert_update_message);
                    if (TextUtils.isEmpty(response.getUpdateInfo().getUpdate_notice()) == false)
                        message = response.getUpdateInfo().getUpdate_notice();
                    if (response.getUpdateInfo().isForced()) {//필수 업데이트
                        mView.showAlert(title, message, new HFDefaultDialog.OnDialogCallback() {
                            @Override
                            public void onNegative() {
                                getActivity().finish();
                            }

                            @Override
                            public void onPositive() {
                                doUpdate(response);
                            }
                        });
                    } else {
                        mView.showAlert(title, message, new HFDefaultDialog.OnDialogCallback() {
                            @Override
                            public void onNegative() {
                                if (response != null && response.isSimpleLoginYn()) {
                                    mView.showSimpleLogin();
                                } else {
                                    mView.showAccountLogin();
                                }
                            }

                            @Override
                            public void onPositive() {
                                doUpdate(response);
                            }
                        });
                    }
                }
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                mView.showAlert(error, new HFSingleDialog.OnDialogCallback() {
                    @Override
                    public void onPositive() {
                        mView.showAccountLogin();
                    }
                });
            }

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

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

    @Override
    public NoticeData checkNotice(@NonNull UpdateData updateData) {
        NoticeData data = null;
        if (updateData != null && updateData.getListPopupNoticeInfos() != null) {
            ArrayList<NoticeData> list = updateData.getListPopupNoticeInfos();
            int index = list.size() - 1;
            if (index >= 0) {
                data = list.get(index);
                int no = data.getId();
                int lastNo = HFInfoUtil.getLastNoticeNo(getContext());
                if (no <= lastNo && lastNo != -1) {
                    data = null;
                }
            }
        }
        return data;

    }

    @Override
    public void doUpdate(UpdateData data) {
        String url = BuildConfig.DOWNLOAD_URL;
        if (TextUtils.isEmpty(data.getUpdateInfo().getUpdate_url()) == false)
            url = data.getUpdateInfo().getUpdate_url();
        try {
            HFActivityUtil.startUrl(getContext(), url);
            HFActivityUtil.startRootActivity(getActivity(), true);
            getActivity().finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doSimpleLogin(@NonNull String authcode) {
        String login_id = HFInfoUtil.getMemberLoginId(getContext());

        MemberDataRepository.getInstance().doSimpleLogin(getContext(), login_id, authcode, new HanwhaNetworkCallback() {
            @Override
            public void onSuccess(Object response) {

                HFActivityUtil.startRootActivity(getActivity(), false);//Root

                HFActivityUtil.startMainActivity(getActivity());
                getActivity().finish();
            }

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

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

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

    @Override
    public void doAccountLogin(@NonNull final String member_id, @NonNull String password) {
        MemberDataRepository.getInstance().doAccountLogin(getContext(), member_id, password, new HanwhaNetworkCallback<LoginData>() {
            @Override
            public void onSuccess(final LoginData response) {
                HFInfoUtil.setMemberLoginId(getContext(), member_id);
                HFInfoUtil.setLastMemberLoginId(getContext(), member_id);

                HFActivityUtil.startRootActivity(getActivity(), false);//Root

                if (response != null && response.isSimpleLoginYn() == false) {
                    HFActivityUtil.startSetEasyLoginActivity(getActivity());
                } else {
                    HFActivityUtil.startMainActivity(getActivity());
                }
                getActivity().finish();
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
//                mView.showAlert(error);
                mView.showAlertAccountMessage(error.getMessage());
                mView.showLoadingDialog(false);
            }

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

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

    @Override
    public void doSignUp() {
        HFActivityUtil.startSignupActivity(getActivity());
    }

    @Override
    public void doSelectDepartment() {
        HFPickerDialog dialog = new HFPickerDialog(getContext());
        dialog.show();
    }

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