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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;

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.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.HFInfoUtil;
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;

    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.setMemberInfo(MemberDataRepository.getInstance().getLoginData());
        mView.setDefaultScreen();

        initDataVersion();

        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() {
        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 doUpdate() {
        final UpdateData updateData = MemberDataRepository.getUpdateData();
        if (updateData == null) return;

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

        mView.showAlert(title, message, new HFDefaultDialog.OnDialogCallback() {
            @Override
            public void onNegative() {
            }

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

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

    /**************************************************
     * CompoundButton.OnCheckedChangeListener
     **************************************************/
    public CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setAlarmSetting(isChecked);
        }
    };

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

    /**************************************************
     * 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.update_textView:
                    doUpdate();
                    break;
                case R.id.version_textView: {
                    testIndex += 1;
                    testHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            testIndex = 0;

                        }
                    }, 5000);
                    if (testIndex > 10 && testIndex < 20) {
                        showAdmin();
                    }
                }
                break;
                case R.id.helpdesk_settingMenuActionView:
                    HFActivityUtil.startHelpdeskActivity(getActivity());
                    break;
            }
        }
    };

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

    private Activity getActivity() {
        return mActivity;
    }


    /**************************************************
     * ADMIN
     **************************************************/
    Handler testHandler = new Handler();
    int testIndex = 0;

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