package com.secureline.server;

import android.util.Base64;
import android.util.Slog;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;

import org.json.JSONObject;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class SecureLineHeartbeatClient {

    private static final String TAG = "SecureLineHeartbeatClient";

    private static final String BASE_URL =
            "https://api-secureline.com";

    private static final int TIMEOUT_MS = 15000;

    private final Context mContext;

    public SecureLineHeartbeatClient(Context context) {
        mContext = context;
    }

    public void sendHeartbeat(
            String deviceId,
            String state,
            int daysLeft,
            String nonce,
            byte[] signature,
            boolean bootloaderLocked,
	    boolean debuggingAllowed,
	    boolean bootloaderUnlockAllowed
    ) throws Exception {

        URL url =
                new URL(BASE_URL + "/v1/device/heartbeat");

        ConnectivityManager cm =
                (ConnectivityManager)
                        mContext.getSystemService(
                                Context.CONNECTIVITY_SERVICE
                        );

        Network network = cm.getActiveNetwork();

        if (network == null) {

            Slog.w(TAG,
                    "No network for heartbeat");

            return;
        }

	javax.net.ssl.HttpsURLConnection conn =
	        (javax.net.ssl.HttpsURLConnection)
	                network.openConnection(url);

	conn.setSSLSocketFactory(
	        SecureLineTlsPinning.getPinnedFactory()
	);

        conn.setRequestMethod("POST");

        conn.setConnectTimeout(TIMEOUT_MS);

        conn.setReadTimeout(TIMEOUT_MS);

        conn.setDoOutput(true);

        conn.setRequestProperty(
                "Content-Type",
                "application/json"
        );

	JSONObject body =
        new JSONObject();

	body.put("device_id", deviceId);

	body.put("state", state);

	body.put("days_left", daysLeft);

	/*
	 * security state
	 */

	body.put(
	        "bootloader_locked",
	        bootloaderLocked
	);

	body.put(
	        "debugging_allowed",
	        debuggingAllowed
	);

	body.put(
	        "bootloader_unlock_allowed",
	        bootloaderUnlockAllowed
	);

	/*
	 * auth
	 */

	body.put("nonce", nonce);

	body.put(
	        "signature",
	        Base64.encodeToString(
	                signature,
	                Base64.NO_WRAP
	        )
	);

        byte[] jsonBytes =
                body.toString().getBytes();

        conn.setFixedLengthStreamingMode(
                jsonBytes.length
        );

        OutputStream os =
                conn.getOutputStream();

        os.write(jsonBytes);

        os.flush();

        os.close();

        int code =
                conn.getResponseCode();

        if (code != 204) {

            Slog.w(
                    TAG,
                    "Heartbeat HTTP " + code
            );

        } else {

            Slog.i(
                    TAG,
                    "Heartbeat sent state=" +
                            state +
                            " days_left=" +
                            daysLeft
            );

        }
    }
}
