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.MaximDataRepository;
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.HFConstants;
import kr.co.hanwha.hifive.util.HFDateUtil;
import kr.co.hanwha.hifive.util.HFDownloadNewVersion;
import kr.co.hanwha.hifive.util.HFInfoUtil;
import kr.co.hanwha.hifive.util.HFNotiUtil;
import timber.log.Timber;

import static kr.co.hanwha.hifive.util.HFDateUtil.FORMAT_EXPIRED_AT;

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

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

    private String mDownloadUrl = BuildConfig.DOWNLOAD_URL;
    private UpdateData mUpdateData;

    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);
        HFInfoUtil.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);
                mUpdateData = response;
                if (HFCommonUtil.checkUpdate(getContext(), response) == false) {
                    showLoginView(response);
                } else {
                    showUpdateAlert();
                }
            }

            @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 void showLoginView(@NonNull UpdateData response) {
        NoticeData notice = checkNotice(response);
        HFInfoUtil.setNoticeData(getContext(), notice);

        if (response != null && response.isSimpleLoginYn()) {
            mView.showSimpleLogin();
        } else {
            mView.showAccountLogin();
        }
    }

    @Override
    public void showUpdateAlert() {
        if (mUpdateData == null) return;

        String title = getContext().getString(R.string.alert_update_title);
        String message = getContext().getString(R.string.alert_update_message);
        if (TextUtils.isEmpty(mUpdateData.getUpdateInfo().getUpdate_notice()) == false)
            message = mUpdateData.getUpdateInfo().getUpdate_notice();

        if (TextUtils.isEmpty(mUpdateData.getUpdateInfo().getUpdate_url()) == false)
            mDownloadUrl = mUpdateData.getUpdateInfo().getUpdate_url();

        if (mUpdateData.getUpdateInfo().isForced()) {//필수 업데이트
            mView.showAlertTypeB(title, message,
                    getContext().getString(R.string.alert_cancel),
                    getContext().getString(R.string.alert_update),
                    new HFDefaultDialog.OnDialogCallback() {
                        @Override
                        public void onNegative() {
                            getActivity().finish();
                        }

                        @Override
                        public void onPositive() {
                            doUpdate();
                        }
                    });
        } else {
            mView.showAlertTypeB(title, message,
                    getContext().getString(R.string.alert_cancel),
                    getContext().getString(R.string.alert_update),
                    new HFDefaultDialog.OnDialogCallback() {
                        @Override
                        public void onNegative() {
                            if (mUpdateData != null && mUpdateData.isSimpleLoginYn()) {
                                mView.showSimpleLogin();
                            } else {
                                mView.showAccountLogin();
                            }
                        }

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

    @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() {
        /*
        try {
            HFActivityUtil.startUrl(getContext(), mDownloadUrl);
            HFActivityUtil.finishApplication(getActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        */

        if (HFCommonUtil.checkPermission(getContext(), getActivity(), HFConstants.REQUEST_CHECK_STORAGE, HFConstants.PERMISSION_STORAGE)) {
            new HFDownloadNewVersion(getContext(),
                    mDownloadUrl,
                    new HFDownloadNewVersion.OnDownloadCallback() {
                        @Override
                        public void onApplicationNeedFinish() {
                            getActivity().finishAffinity();
//                            HFActivityUtil.finishApplication(getActivity());
                        }
                    });
        }
    }

    @Override
    public void showPermissionAlert() {
        mView.showAlert(getContext().getString(R.string.alert_default_title),
                getContext().getString(R.string.alert_need_permission_storage),
                getContext().getString(R.string.alert_cancel),
                getContext().getString(R.string.alert_setting),
                new HFDefaultDialog.OnDialogCallback() {
                    @Override
                    public void onNegative() {
                        showUpdateAlert();
                    }

                    @Override
                    public void onPositive() {
                        HFActivityUtil.startApplicationSetting(getActivity());
                        getActivity().finishAffinity();
//                        HFActivityUtil.finishApplication(getActivity());
//                        getActivity().finish();
                    }
                });
    }

    @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) {
                getMaximList(false);
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                String errorMessage = error.getMessage().isEmpty() ? getContext().getString(R.string.alert_default_message) : error.getMessage();
                mView.showAlertSimpleMessage(errorMessage);
                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) {
                if (response == null) {
                    onFailure(new HanwhaNetworkError());
                    return;
                }

                HFInfoUtil.setMemberLoginId(getContext(), member_id);
                HFInfoUtil.setLastMemberLoginId(getContext(), member_id);

                checkExpiredAccount(response);
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                String errorMessage = error.getMessage().isEmpty() ? getContext().getString(R.string.alert_default_message) : error.getMessage();
                mView.showAlertAccountMessage(errorMessage);
                mView.showLoadingDialog(false);
            }

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

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

    @Override
    public void getMaximList(@NonNull final boolean needSetSimpleLogin) {
        MaximDataRepository.getInstance().requestMaximList(getContext(), new HanwhaNetworkCallback() {
            @Override
            public void onSuccess(Object response) {
                startMain(needSetSimpleLogin);
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                startMain(needSetSimpleLogin);
            }

            @Override
            public void onPreExecute() {

            }

            @Override
            public void onPostExecute() {

            }
        });
    }

    @Override
    public void startMain(@NonNull final boolean needSetSimpleLogin) {
//        HFActivityUtil.startRootActivity(getActivity());//Root

        if (needSetSimpleLogin) {
            HFActivityUtil.startSetEasyLoginActivity(getActivity());
        } else {
            HFActivityUtil.startMainActivity(getActivity());
        }
        getActivity().finish();
    }

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

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

    @Override
    public void checkExpiredAccount(@NonNull LoginData response) {
        Timber.i("expired_at string: %s", response.getExpired_at());
        Timber.i("expired_at: %d, today: %d", HFDateUtil.getTimestampFromStringFormat(response.getExpired_at(), FORMAT_EXPIRED_AT), HFDateUtil.getTimestampToday());
        if (HFDateUtil.getTimestampFromStringFormat(response.getExpired_at(), FORMAT_EXPIRED_AT) < HFDateUtil.getTimestampToday()) {
            Timber.i("Account expired!!!");
            HFActivityUtil.startLoginChangeTemporaryPasswordWebviewActivity(getActivity(), response.isSimpleLoginYn());
        } else {
            Timber.i("Account is valid!!!");
            getMaximList(response.isSimpleLoginYn() == false);
        }
    }

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