package com.ttstd.controller.activity.login;

import android.text.TextUtils;

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

import com.ttstd.controller.base.mvvm.BaseViewModel;
import com.ttstd.controller.network.AuthRepository;
import com.ttstd.controller.utils.TokenStore;

import retrofit2.HttpException;

/**
 * 登录页 ViewModel：用户名密码登录。
 *
 * <p>网络请求通过 Retrofit 返回 Single，由基类 CompositeDisposable 托管，
 * 页面销毁自动取消订阅。
 */
public class LoginViewModel extends BaseViewModel {

    private final AuthRepository repository = new AuthRepository();

    private final MutableLiveData<Boolean> loading = new MutableLiveData<>(false);
    private final MutableLiveData<Boolean> loginSuccess = new MutableLiveData<>();
    private final MutableLiveData<String> errorMessage = new MutableLiveData<>();

    public LiveData<Boolean> getLoading() {
        return loading;
    }

    public LiveData<Boolean> getLoginSuccess() {
        return loginSuccess;
    }

    public LiveData<String> getErrorMessage() {
        return errorMessage;
    }

    /** 回显上次登录的用户名。 */
    public String lastUsername() {
        return TokenStore.get().getUsername();
    }

    public void login(String username, String password) {
        if (TextUtils.isEmpty(username)) {
            errorMessage.setValue("请输入用户名");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            errorMessage.setValue("请输入密码");
            return;
        }
        if (Boolean.TRUE.equals(loading.getValue())) {
            return;
        }

        loading.setValue(true);
        execute(
                repository.login(username.trim(), password),
                token -> {
                    loading.setValue(false);
                    loginSuccess.setValue(true);
                },
                error -> {
                    loading.setValue(false);
                    errorMessage.setValue(parseError(error));
                });
    }

    private String parseError(Throwable error) {
        if (error instanceof HttpException) {
            int code = ((HttpException) error).code();
            if (code == 401 || code == 400) {
                return "用户名或密码错误";
            }
            if (code == 429) {
                return "尝试过于频繁，请稍后再试";
            }
            return "登录失败（HTTP " + code + "）";
        }
        String msg = error.getMessage();
        return TextUtils.isEmpty(msg) ? "网络异常，请检查服务器地址" : msg;
    }
}
