// File: ScreensaverManager.java
package com.dspread.pos.common.manager;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;

import com.dspread.pos.ui.screensaver.ScreensaverActivity;

public class ScreensaverManager {
    private static final String TAG = "ScreensaverManager";
    private static final long SCREENSAVER_TIMEOUT = 1200000; // 30 seconds

    private final Handler handler = new Handler(Looper.getMainLooper());
    private final Runnable screensaverRunnable;
    private final Context context;
    private final MutableLiveData<Boolean> isScreensaverActive = new MutableLiveData<>(false);

    public ScreensaverManager(Context context) {
        this.context = context;
        this.screensaverRunnable = this::startScreensaver;
    }

    public void resetTimer() {
        Log.d(TAG, "Resetting screensaver timer");
        handler.removeCallbacks(screensaverRunnable);
        if (!Boolean.TRUE.equals(isScreensaverActive.getValue())) {
            handler.postDelayed(screensaverRunnable, SCREENSAVER_TIMEOUT);
        }
    }

    public void cancelTimer() {
        Log.d(TAG, "Cancelling screensaver timer");
        handler.removeCallbacks(screensaverRunnable);
    }

    private void startScreensaver() {
        Log.d(TAG, "Starting screensaver");
        isScreensaverActive.postValue(true);
        // Start your ScreensaverActivity here
         Intent intent = new Intent(context, ScreensaverActivity.class);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(intent);
    }

    public void stopScreensaver() {
        Log.d(TAG, "Stopping screensaver");
        isScreensaverActive.postValue(false);
    }

    public MutableLiveData<Boolean> getIsScreensaverActive() {
        return isScreensaverActive;
    }

    public void cleanup() {
        cancelTimer();
    }
}