package com.example.tampopo_client.viewmodels;

import androidx.lifecycle.ViewModel;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * {@code onUpdate()}が1秒毎に呼び出されます。
 *
 * @author Shohei Yamagiwa
 */
public abstract class RealTimeViewModel extends ViewModel {
    private final ScheduledExecutorService updateScheduler;
    private ScheduledFuture<?> updateTask;

    public RealTimeViewModel() {
        updateScheduler = Executors.newSingleThreadScheduledExecutor();
    }

    public abstract Runnable onUpdate();

    @Override
    protected void onCleared() {
        super.onCleared();

        stopUpdating();
    }

    /**
     * 定期的に{@code onUpdate()}を呼び出す
     *
     * @param delay 定期実行の間隔（秒）
     */
    public void startUpdating(long delay) {
        if (updateTask != null && !updateTask.isDone()) {
            return;
        }
        updateTask = updateScheduler.scheduleWithFixedDelay(this.onUpdate(), 0, delay, TimeUnit.SECONDS);
    }

    /**
     * 定期実行を停止する
     */
    public void stopUpdating() {
        if (updateScheduler != null) {
            updateScheduler.shutdownNow();
        }
    }
}
