package com.ttstd.controller.base;

import android.content.Intent;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;
import androidx.lifecycle.ViewModelStore;
import androidx.lifecycle.ViewModelStoreOwner;

import com.ttstd.controller.base.rx.BaseRxService;

import org.jetbrains.annotations.NotNull;

/**
 * Service 基类。
 *
 * 同时实现 LifecycleOwner 与 ViewModelStoreOwner：
 * - LifecycleOwner 让 LiveData.observe(this, ...) 可用；
 * - ViewModelStoreOwner 让 ViewModelProvider 创建的 ViewModel 在 onDestroy
 *   时收到 onCleared 回调，从而自动 dispose 其中的网络请求。
 */
public abstract class BaseService extends BaseRxService implements LifecycleOwner, ViewModelStoreOwner {

    private final LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);
    private final ViewModelStore viewModelStore = new ViewModelStore();

    @NotNull
    @Override
    public Lifecycle getLifecycle() {
        return lifecycleRegistry;
    }

    @NotNull
    @Override
    public ViewModelStore getViewModelStore() {
        return viewModelStore;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        //修补在Service中LiveData不能触发
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
        // 触发 ViewModel.onCleared()，取消所有在途请求
        viewModelStore.clear();
    }
}
