package kr.co.hanwha.hifive.screen.main.setting;

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

import kr.co.hanwha.hifive.BuildConfig;
import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.admin.AdminInputDialog;
import kr.co.hanwha.hifive.admin.TestModeActivity;
import kr.co.hanwha.hifive.data.model.CrudDataRoot;
import kr.co.hanwha.hifive.data.model.MemberHrDataRoot;
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.network.HFNetworkUtil;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkCallback;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkError;
import kr.co.hanwha.hifive.screen.main.setting.contract.MainSettingContract;
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.HFDownloadNewVersion;
import kr.co.hanwha.hifive.util.HFInfoUtil;
import kr.co.hanwha.hifive.view.HFSettingMenuActionView;
import kr.co.hanwha.hifive.view.HFSettingMenuVersionView;
import kr.co.hanwha.hifive.view.HFSettingProfileView;

public class MainSettingPresenter implements MainSettingContract.Presenter {
    private Activity mActivity;
    private Context mContext;
    private MainSettingContract.View mView;
    private boolean mLastChecked = false;
    private String mDownloadUrl = BuildConfig.DOWNLOAD_URL;

    public MainSettingPresenter(@NonNull Activity activity, @NonNull Context context, MainSettingContract.View view) {
        mActivity = activity;
        mContext = context;
        mView = view;
    }

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

    @Override
    public void initData() {

        mView.setDefaultScreen();

        initDataVersion();

        initMemberHrInfo(true);
    }

    @Override
    public void initMemberHrInfo(final boolean needNotification) {
        MemberDataRepository.getInstance().getMemberHrInfo(getContext(), new HanwhaNetworkCallback<MemberHrDataRoot>() {
            @Override
            public void onSuccess(MemberHrDataRoot response) {
                if (response != null) {
                    String loginId = response.getLogin();
                    String memberName = MemberDataRepository.getInstance().getLoginData().getName();
                    String rank = response.getRank();
                    mView.setMemberInfo(memberName, loginId, rank);
                }
            }

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

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

            @Override
            public void onPostExecute() {
                if (needNotification)
                    initNotificationStatus();
                else
                    mView.showLoadingDialog(false);
            }
        });
    }

    @Override
    public void initNotificationStatus() {
        MemberDataRepository.getInstance().getNotificationStatus(getContext(), new HanwhaNetworkCallback<CrudDataRoot>() {
            @Override
            public void onSuccess(CrudDataRoot response) {
                if (response != null) {
                    mLastChecked = response.getOnOff();
                    mView.setAlarmSetting(mLastChecked);
                } else {
                    mView.setAlarmSetting(false);
                }
            }

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

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

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

    private void initDataVersion() {
        String lastVersion = MemberDataRepository.getLastVersion();
        String currentVersion = HFCommonUtil.getAppVersion(getActivity());
        String rc = "-" + BuildConfig.RC;
        String revision = " (r" + BuildConfig.REVISION + ")";
        String displayVersion = "v" + currentVersion + rc + revision;

        boolean needUpdate = (lastVersion.compareTo(currentVersion) > 0);

        mView.setVersion(displayVersion, needUpdate);
    }

    @Override
    public void doEditProfileManagement() {
        HFInfoUtil.setNeedRefreshMainSettingHr(getContext());
        HFActivityUtil.startMainSettingEditProfileWebviewActivity(getActivity());
    }

    @Override
    public void doPasswordManagement() {
        HFActivityUtil.startMainSettingEditPasswordWebviewActivity(getActivity());
    }

    @Override
    public void doSimplePasswordManagement() {
        HFActivityUtil.startMainSettingDeleteSimplePasswordWebviewActivity(getActivity());
    }

    @Override
    public void doUnitManagement(@NonNull int projectId) {
        HFNetworkUtil networkUtil = new HFNetworkUtil();
        String encryption = MemberDataRepository.getInstance().getEncryptionMemberId();
        String url = networkUtil.getWebUrlSettingEditUnit();
        HFActivityUtil.startIssueEditActivity(getActivity(),
                url,
                encryption,
                projectId);
    }

    @Override
    public void showUpdateAlert() {
        final UpdateData updateData = MemberDataRepository.getUpdateData();
        if (updateData == null) return;
        String title = getContext().getString(R.string.alert_update_title);
        String message = getContext().getString(R.string.alert_update_message);
        if (TextUtils.isEmpty(updateData.getUpdateInfo().getUpdate_notice()) == false)
            message = updateData.getUpdateInfo().getUpdate_notice();
        if (TextUtils.isEmpty(updateData.getUpdateInfo().getUpdate_url()) == false)
            mDownloadUrl = updateData.getUpdateInfo().getUpdate_url();

        mView.showAlertTypeB(title, message,
                getContext().getString(R.string.alert_cancel),
                getContext().getString(R.string.alert_update),
                new HFDefaultDialog.OnDialogCallback() {
                    @Override
                    public void onNegative() {
                    }

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

    @Override
    public void doUpdate() {
        /*
        try {
            HFActivityUtil.startUrl(getContext(), mDownloadUrl);
            HFActivityUtil.finishApplication(getActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        */
        if (HFCommonUtil.checkPermission(getContext(), getActivity(), (Fragment) mView, 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() {

                    }

                    @Override
                    public void onPositive() {
                        HFActivityUtil.startApplicationSetting(getActivity());
                    }
                });
    }

    @Override
    public void setAlarmSetting(boolean isSelected) {
        if (mLastChecked == isSelected) return;
        MemberDataRepository.getInstance().setNotificationStatus(getContext(), isSelected, new HanwhaNetworkCallback<CrudDataRoot>() {
            @Override
            public void onSuccess(CrudDataRoot response) {
                if (response != null) {
                    mLastChecked = response.getOnOff();
                    mView.setAlarmSetting(mLastChecked);
                } else {
                    mView.setAlarmSetting(false);
                }
            }

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

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

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

    /**************************************************
     * HFSettingProfileView.OnSettingProfileListener
     **************************************************/
    HFSettingProfileView.OnSettingProfileListener onSettingProfileListener = new HFSettingProfileView.OnSettingProfileListener() {
        @Override
        public void onEasterEggClicked() {
            HFInfoUtil.setMemberLoginId(getActivity(), "");
            HFActivityUtil.startIntroActivity(getActivity());
        }

        @Override
        public void onMyHomeClicked() {
            HFActivityUtil.startMyHomeActivity(getActivity(), MemberDataRepository.getInstance().getLoginData().getMember_id());
        }
    };

    /**************************************************
     * HFSettingMenuActionView.OnSettingMenuActionListener
     **************************************************/
    HFSettingMenuActionView.OnSettingMenuActionListener onSettingMenuActionListener = new HFSettingMenuActionView.OnSettingMenuActionListener() {
        @Override
        public void onCheckedChanged(boolean isChecked) {
            setAlarmSetting(isChecked);
        }
    };

    /**************************************************
     * HFSettingMenuActionView.OnSettingMenuActionListener
     **************************************************/
    HFSettingMenuVersionView.OnSettingMenuVersionListener onSettingMenuVersionListener = new HFSettingMenuVersionView.OnSettingMenuVersionListener() {
        @Override
        public void onUpdateClicked() {
            showUpdateAlert();
        }

        @Override
        public void onEasterEggClicked() {
            showAdmin();
        }
    };

    /**************************************************
     * View.OnClickListener
     **************************************************/
    public View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.editProfile_settingMenuActionView:
                    doEditProfileManagement();
                    break;
                case R.id.password_settingMenuActionView:
                    doPasswordManagement();
                    break;
                case R.id.simplePassword_settingMenuActionView:
                    doSimplePasswordManagement();
                    break;
                case R.id.tab_settingMenuActionView:
                    HFActivityUtil.startSettingScreenActivity(getActivity());
                    break;
                case R.id.helpdesk_settingMenuActionView:
                    HFActivityUtil.startHelpdeskActivity(getActivity());
                    break;
            }
        }
    };

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

    private Activity getActivity() {
        return mActivity;
    }


    /**************************************************
     * ADMIN
     **************************************************/
    private void showAdmin() {
        new AdminInputDialog(getActivity(), AdminInputDialog.ADMIN_TYPE.PASSWORD, new AdminInputDialog.OnDialogCallback() {
            @Override
            public void onPositive(@NonNull String message) {
                Intent intent = new Intent(getActivity(), TestModeActivity.class);
                getActivity().startActivity(intent);
            }

            @Override
            public void onWrongPassword() {
                mView.showToast("Wrong password");
            }
        }).show();
    }
}
