package com.lemenzo.messenger.mms;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.google.android.mms.pdu.GenericPdu;
import com.google.android.mms.pdu.NotificationInd;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public final class MmsPduBridge {
    private static final String TAG = "LemenzoMessengerMms";
    private MmsPduBridge() {}

    public static void onIncomingNotification(Context context, int subscriptionId, byte[] pduBytes) {
        GenericPdu parsed = MmsPduUtils.parse(pduBytes);
        if (!(parsed instanceof NotificationInd)) {
            Log.w(TAG, "Ignoring non-NotificationInd WAP PDU");
            return;
        }

        NotificationInd notification = (NotificationInd) parsed;
        byte[] locationBytes = notification.getContentLocation();
        if (locationBytes == null || locationBytes.length == 0) {
            Log.w(TAG, "NotificationInd missing content-location");
            return;
        }

        String location = new String(locationBytes, StandardCharsets.ISO_8859_1);
        MmsConfig config = MmsConfig.forSubscription(context, subscriptionId);
        byte[] transaction = notification.getTransactionId();
        if (config.appendTransactionId && transaction != null && transaction.length > 0
                && !location.endsWith("=" + new String(transaction, StandardCharsets.ISO_8859_1))) {
            location = location + "=" + new String(transaction, StandardCharsets.ISO_8859_1);
        }

        String token = UUID.randomUUID().toString();
        new MmsDownloadStore(context).put(token, location, subscriptionId);
        if (!startDownload(context, token)) {
            new MmsDownloadStore(context).markFailed(token);
            com.lemenzo.messenger.notifications.MessageNotificationManager
                    .notifyMmsDownloadFailed(context, token);
        }
    }

    public static boolean retryDownload(Context context, String token) {
        boolean accepted = startDownload(context, token);
        if (!accepted) {
            new MmsDownloadStore(context).markFailed(token);
            com.lemenzo.messenger.notifications.MessageNotificationManager
                    .notifyMmsDownloadFailed(context, token);
        }
        return accepted;
    }

    private static boolean startDownload(Context context, String token) {
        MmsDownloadStore.Entry entry = new MmsDownloadStore(context).get(token);
        if (entry == null || entry.location == null || entry.location.isEmpty()) return false;

        Uri target = MmsFileProvider.createUri(context, "download");
        Intent result = new Intent(context, MmsDownloadResultReceiver.class)
                .setAction(MmsDownloadResultReceiver.ACTION_MMS_DOWNLOADED)
                .putExtra("content_uri", target.toString())
                .putExtra("subscription_id", entry.subscriptionId)
                .putExtra("download_token", token);

        PendingIntent pending = PendingIntent.getBroadcast(context,
                (token + ":download").hashCode(), result,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        boolean accepted = MmsTransport.download(context, entry.subscriptionId,
                entry.location, target, pending);
        if (!accepted) MmsFileProvider.delete(context, target);
        return accepted;
    }
}
