package com.lemenzo.messenger.mms;

import android.app.PendingIntent;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SubscriptionManager;

/**
 * Thin wrapper around Android's platform MMS transport.
 *
 * Android's SmsManager performs the carrier/MMSC network operation. Lemenzo Messenger
 * still needs a PDU parser/composer/persister layer to turn WAP push notifications
 * into content-location URLs and to create/read actual MMS PDUs.
 */
public final class MmsTransport {
    private MmsTransport() {}

    private static SmsManager manager(Context context, int subscriptionId) {
        SmsManager base = context.getSystemService(SmsManager.class);
        if (base == null) return null;
        return subscriptionId == SubscriptionManager.INVALID_SUBSCRIPTION_ID
                ? base
                : base.createForSubscriptionId(subscriptionId);
    }

    public static boolean download(
            Context context,
            int subscriptionId,
            String contentLocation,
            Uri destination,
            PendingIntent resultIntent) {
        if (contentLocation == null || contentLocation.isEmpty() || destination == null) {
            return false;
        }

        SmsManager manager = manager(context, subscriptionId);
        if (manager == null) return false;

        try {
            Bundle carrierOverrides = manager.getCarrierConfigValues();
            manager.downloadMultimediaMessage(
                    context,
                    contentLocation,
                    destination,
                    carrierOverrides,
                    resultIntent);
            return true;
        } catch (RuntimeException e) {
            return false;
        }
    }

    public static boolean send(
            Context context,
            int subscriptionId,
            Uri pduUri,
            String locationUrl,
            PendingIntent resultIntent) {
        if (pduUri == null) return false;

        SmsManager manager = manager(context, subscriptionId);
        if (manager == null) return false;

        try {
            Bundle carrierOverrides = manager.getCarrierConfigValues();
            manager.sendMultimediaMessage(
                    context,
                    pduUri,
                    locationUrl,
                    carrierOverrides,
                    resultIntent);
            return true;
        } catch (RuntimeException e) {
            return false;
        }
    }
}
