package com.foxx.androidcast.remoteaccess;

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

import com.foxx.androidcast.AppPreferences;
import com.foxx.androidcast.vpn.VpnServiceClient;

/** Start/stop remote access foreground polling + VPN based on developer mode. */
public final class RemoteAccessCoordinator {
    private static final String TAG = "RemoteAccessCoord";

    private RemoteAccessCoordinator() {}

    public static void applyMode(Context context, RemoteAccessMode mode) {
        Context app = context.getApplicationContext();
        if (mode == null || mode == RemoteAccessMode.DISABLED) {
            Log.i(TAG, "disabling remote access");
            RemoteAccessService.sendDisableOnce(app);
            RemoteAccessService.stop(app);
            VpnServiceClient.get(app).tearDown();
            AppPreferences.clearDevRemoteAccessSession(app);
            RemoteAccessStatusStore.record(
                    app,
                    RemoteAccessMode.DISABLED,
                    RemoteAccessStatusStore.STATE_OFF,
                    "RemoteAccessCoordinator.applyMode",
                    RemoteAccessStatusStore.INITIATOR_USER,
                    "",
                    "");
            return;
        }
        if (mode == RemoteAccessMode.WIREGUARD || mode == RemoteAccessMode.RSSH) {
            RemoteAccessService.start(app, mode);
            return;
        }
        Log.w(TAG, "unsupported mode " + mode);
    }

    public static void syncFromPreferences(Context context) {
        applyMode(context, AppPreferences.getDevRemoteAccessMode(context));
    }

    public static void onBootIfNeeded(Context context) {
        RemoteAccessMode mode = AppPreferences.getDevRemoteAccessMode(context);
        if (mode.isActive()) {
            RemoteAccessService.start(context.getApplicationContext(), mode);
        }
    }
}
