package com.datarecovery.master.module.mine;

import android.text.TextUtils;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;

import com.atmob.app.lib.base.BaseViewModel;
import com.atmob.app.lib.livedata.SingleLiveEvent;
import com.atmob.common.data.KVUtils;
import com.atmob.common.runtime.ActivityUtil;
import com.atmob.common.runtime.ContextUtil;
import com.datarecovery.master.R;
import com.datarecovery.master.data.consts.ChannelHelper;
import com.datarecovery.master.data.consts.ChannelId;
import com.datarecovery.master.data.consts.EventId;
import com.datarecovery.master.data.repositories.AccountRepository;
import com.datarecovery.master.data.repositories.ConfigRepository;
import com.datarecovery.master.data.repositories.DeviceFuncRepository;
import com.datarecovery.master.handler.EventHelper;
import com.datarecovery.master.module.about.AboutActivity;
import com.datarecovery.master.module.feedback.UserFeedbackActivity;
import com.datarecovery.master.module.imgrecover.ImageRecoverActivity;
import com.datarecovery.master.module.member.MemberType;
import com.datarecovery.master.utils.Maps;
import com.datarecovery.master.utils.RxHttpHandler;
import com.datarecovery.master.utils.ToastUtil;

import javax.inject.Inject;

import atmob.reactivex.rxjava3.annotations.NonNull;
import atmob.reactivex.rxjava3.core.SingleObserver;
import atmob.reactivex.rxjava3.disposables.Disposable;
import dagger.hilt.android.lifecycle.HiltViewModel;


@HiltViewModel
public class MineViewModel extends BaseViewModel {

    private final MutableLiveData<Boolean> showLoading = new MutableLiveData<>();
    private final SingleLiveEvent<?> showExitDialog = new SingleLiveEvent<>();
    private final SingleLiveEvent<?> showLogoutDialog = new SingleLiveEvent<>();
    private final MutableLiveData<String> mineAppealText = new MutableLiveData<>();
    private final MutableLiveData<String> userId = new MutableLiveData<>();
    private final LiveData<String> loginTips;

    private final AccountRepository accountRepository;
    private final DeviceFuncRepository deviceFuncRepository;
    private final ConfigRepository configRepository;


    @Inject
    public MineViewModel(AccountRepository accountRepository, DeviceFuncRepository deviceFuncRepository, ConfigRepository configRepository) {
        this.accountRepository = accountRepository;
        this.configRepository = configRepository;
        this.deviceFuncRepository = deviceFuncRepository;
        loginTips = Transformations.map(accountRepository.getLoginPhoneNum(), phone -> {
            if (TextUtils.isEmpty(phone)) {
                return ContextUtil.getContext().getString(R.string.mine_no_login);
            } else {
                if (phone.length() > 4) {
                    phone = phone.substring(phone.length() - 4);
                }
                return ContextUtil.getContext().getString(R.string.mine_logged, phone);
            }
        });
        if (ChannelHelper.isTargetSuffixChannel(ChannelId.HUAWEI)) {
            mineAppealText.setValue(ContextUtil.getContext().getString(R.string.mine_appeal_hw));
        } else {
            mineAppealText.setValue(ContextUtil.getContext().getString(R.string.mine_appeal));
        }
        setUserId();
    }

    public LiveData<String> getMineAppealText() {
        return mineAppealText;
    }

    public LiveData<Boolean> getShowLoading() {
        return showLoading;
    }

    public LiveData<?> getShowExitDialog() {
        return showExitDialog;
    }

    public LiveData<?> getShowLogoutDialog() {
        return showLogoutDialog;
    }

    public LiveData<String> getLoginTips() {
        return loginTips;
    }

    public LiveData<String> getUserId() {
        return userId;
    }

    private void setUserId() {
        String userIdCache = KVUtils.getDefault().getString("user_id", "");
        if (TextUtils.isEmpty(userIdCache)) {
            String newUserId = (int) (Math.random() * 1000) + "***" + (int) (Math.random() * 1000);
            userId.setValue(newUserId);
            KVUtils.getDefault().putString("user_id", newUserId);
        } else {
            userId.setValue(userIdCache);
        }
    }

    public void onAboutClick() {
        AboutActivity.start(ActivityUtil.getTopActivity());

        EventHelper.report(EventId.EVENT_3020001);
    }

    public void onAccountExit() {
        accountRepository.requestUserLogout();
    }

    public void onAccountLogout() {
        accountRepository.userDeprecate().subscribe(new SingleObserver<Object>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                addDisposable(d);
            }

            @Override
            public void onSuccess(@NonNull Object object) {
                ToastUtil.show(R.string.account_logout_success, ToastUtil.LENGTH_SHORT);
                accountRepository.logout();
            }

            @Override
            public void onError(@NonNull Throwable throwable) {
                if (throwable instanceof RxHttpHandler.ServerErrorException) {
                    RxHttpHandler.ServerErrorException serverErrorException = (RxHttpHandler.ServerErrorException) throwable;
                    ToastUtil.show(serverErrorException.getMsg(), ToastUtil.LENGTH_SHORT);
                } else {
                    ToastUtil.show(R.string.net_error, ToastUtil.LENGTH_SHORT);
                }
            }
        });
    }

    public void onFeedbackClick() {
        UserFeedbackActivity.start(ActivityUtil.getTopActivity());
        EventHelper.report(EventId.EVENT_3020002);
    }

    public void onMemberClick() {
        ImageRecoverActivity.start(ActivityUtil.getTopActivity(), MemberType.APP_IMAGE_RECOVER);
        EventHelper.report(EventId.EVENT_3000005, Maps.asMap("id", 105));
    }
}
