package com.ttstd.controlled.service;

import android.content.Context;
import android.util.Log;

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

import com.ttstd.controlled.base.mvvm.BaseViewModel;
import com.ttstd.controlled.network.DeviceRepository;

/**
 * ScreenCaptureService 的 ViewModel。
 *
 * 负责设备激活（provision + token）与令牌刷新的全部网络交互，
 * 通过 Retrofit + RxJava3 发起请求，并由 BaseViewModel 的 CompositeDisposable
 * 在 onCleared（Service 销毁）时自动取消，不再使用 new Thread。
 */
public class ScreenCaptureModel extends BaseViewModel {

    private static final String TAG = "ScreenCaptureModel";

    private DeviceRepository repository;

    /** 激活成功，携带 accessToken。 */
    private final MutableLiveData<String> activateSuccess = new MutableLiveData<>();
    /** 激活失败，携带原因。 */
    private final MutableLiveData<String> activateFailed = new MutableLiveData<>();
    /** 令牌刷新成功，携带新的 accessToken。 */
    private final MutableLiveData<String> tokenRefreshed = new MutableLiveData<>();
    /** 令牌刷新失败，携带原因。 */
    private final MutableLiveData<String> tokenRefreshFailed = new MutableLiveData<>();

    public void init(Context context) {
        if (repository == null) {
            repository = new DeviceRepository(context);
        }
    }

    public LiveData<String> getActivateSuccess() {
        return activateSuccess;
    }

    public LiveData<String> getActivateFailed() {
        return activateFailed;
    }

    public LiveData<String> getTokenRefreshed() {
        return tokenRefreshed;
    }

    public LiveData<String> getTokenRefreshFailed() {
        return tokenRefreshFailed;
    }

    public String getDeviceUid() {
        return repository != null ? repository.getDeviceUid() : null;
    }

    public boolean isActivated() {
        return repository != null && repository.isActivated();
    }

    /**
     * 确保设备已激活：已激活则直接换取 accessToken，否则先 provision 再换取。
     */
    public void activate() {
        if (repository == null) {
            activateFailed.setValue("仓库未初始化");
            return;
        }
        execute(repository.activate(),
                token -> {
                    Log.i(TAG, "激活成功，deviceUid=" + repository.getDeviceUid());
                    activateSuccess.setValue(token);
                },
                error -> {
                    Log.e(TAG, "激活失败", error);
                    activateFailed.setValue(message(error));
                });
    }

    /**
     * 令牌失效（4001）时重新换取 accessToken。
     */
    public void refreshToken() {
        if (repository == null) {
            tokenRefreshFailed.setValue("仓库未初始化");
            return;
        }
        execute(repository.activate(),
                token -> {
                    Log.i(TAG, "令牌刷新成功");
                    tokenRefreshed.setValue(token);
                },
                error -> {
                    Log.e(TAG, "令牌刷新失败", error);
                    tokenRefreshFailed.setValue(message(error));
                });
    }

    private static String message(Throwable error) {
        String msg = error != null ? error.getMessage() : null;
        return msg == null || msg.isEmpty() ? "未知错误" : msg;
    }
}
