package ai.z.chat;

import android.content.Context;
import android.os.PowerManager;
import android.view.WindowManager;

import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;

@CapacitorPlugin(name = "Wake")
public class WakePlugin extends Plugin {
    private PowerManager.WakeLock screenWakeLock;
    private PowerManager.WakeLock cpuWakeLock;
    private volatile boolean isHeld = false;

    @Override
    public void load() {
        super.load();
    }

    @PluginMethod
    public void acquire(PluginCall call) {
        if (isHeld) {
            call.resolve(new JSObject().put("held", true));
            return;
        }

        try {
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    if (getActivity() != null) {
                        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                    }
                });
            }

            PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
            if (pm == null) {
                call.reject("Power service unavailable");
                return;
            }

            screenWakeLock = pm.newWakeLock(
                PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
                "zai-chat:screen"
            );
            screenWakeLock.acquire(24 * 60 * 60 * 1000L);

            cpuWakeLock = pm.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK,
                "zai-chat:cpu"
            );
            cpuWakeLock.acquire(24 * 60 * 60 * 1000L);

            isHeld = true;
            call.resolve(new JSObject().put("held", true));
        } catch (Exception e) {
            call.reject("Wake lock failed: " + e.getMessage());
        }
    }

    @PluginMethod
    public void release(PluginCall call) {
        try {
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    if (getActivity() != null) {
                        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                    }
                });
            }

            if (screenWakeLock != null && screenWakeLock.isHeld()) {
                screenWakeLock.release();
            }
            screenWakeLock = null;

            if (cpuWakeLock != null && cpuWakeLock.isHeld()) {
                cpuWakeLock.release();
            }
            cpuWakeLock = null;

            isHeld = false;
            call.resolve(new JSObject().put("held", false));
        } catch (Exception e) {
            call.reject("Wake release failed: " + e.getMessage());
        }
    }

    @PluginMethod
    public void isHeld(PluginCall call) {
        call.resolve(new JSObject().put("held", isHeld));
    }
}
