package com.lemenzo.messenger.notifications;

import android.app.NotificationManager;
import android.app.RemoteInput;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.telephony.SubscriptionManager;
import android.widget.Toast;
import com.lemenzo.messenger.R;
import com.lemenzo.messenger.data.MessageRepository;
import com.lemenzo.messenger.sms.SmsSender;
import com.lemenzo.messenger.util.ReceiverAsync;

public final class NotificationActionReceiver extends BroadcastReceiver {
    public static final String ACTION_MARK_READ = "com.lemenzo.messenger.MARK_READ";
    public static final String ACTION_REPLY = "com.lemenzo.messenger.REPLY";
    public static final String ACTION_RETRY_MMS_DOWNLOAD = "com.lemenzo.messenger.RETRY_MMS_DOWNLOAD";

    @Override
    public void onReceive(Context context, Intent intent) {
        final Context appContext = context.getApplicationContext();
        final String action = intent.getAction();
        final long threadId = intent.getLongExtra("thread_id", -1);
        final int notificationId = intent.getIntExtra("notification_id", -1);

        if (ACTION_MARK_READ.equals(action)) {
            ReceiverAsync.run(this, () -> markRead(appContext, threadId, notificationId));
            return;
        }

        if (ACTION_RETRY_MMS_DOWNLOAD.equals(action)) {
            final String token = intent.getStringExtra("download_token");
            if (token == null) return;
            ReceiverAsync.run(this, () -> {
                if (com.lemenzo.messenger.mms.MmsPduBridge.retryDownload(appContext, token)) {
                    NotificationManager nm = appContext.getSystemService(NotificationManager.class);
                    if (nm != null && notificationId >= 0) nm.cancel(notificationId);
                }
            });
            return;
        }

        if (ACTION_REPLY.equals(action)) {
            Bundle results = RemoteInput.getResultsFromIntent(intent);
            CharSequence reply = results == null
                    ? null
                    : results.getCharSequence(MessageNotificationManager.REMOTE_INPUT_KEY);
            final String address = intent.getStringExtra("address");
            final int subscriptionId = intent.getIntExtra(
                    "subscription_id",
                    SubscriptionManager.INVALID_SUBSCRIPTION_ID);

            if (reply == null || address == null || reply.toString().trim().isEmpty()) {
                return;
            }

            final String replyText = reply.toString();
            ReceiverAsync.run(this, () -> {
                boolean accepted = SmsSender.send(
                        appContext,
                        address,
                        replyText,
                        subscriptionId);

                if (accepted) {
                    markRead(appContext, threadId, notificationId);
                } else {
                    new Handler(Looper.getMainLooper()).post(() -> Toast.makeText(
                            appContext,
                            R.string.message_delivery_failed,
                            Toast.LENGTH_LONG).show());
                }
            });
        }
    }

    private static void markRead(Context context, long threadId, int notificationId) {
        if (threadId > 0) {
            new MessageRepository(context).markThreadRead(threadId);
        }

        NotificationManager nm = context.getSystemService(NotificationManager.class);
        if (nm != null && notificationId >= 0) {
            nm.cancel(notificationId);
        }
    }
}
