package ch.threema.app.actions;

import org.slf4j.Logger;

import java.util.ArrayList;

import ch.threema.app.messagereceiver.MessageReceiver;
import ch.threema.app.services.MessageService;
import ch.threema.app.utils.MessageUtil;
import ch.threema.app.utils.TextUtil;
import static ch.threema.base.utils.LoggingKt.getThreemaLogger;
import static ch.threema.common.JavaCompat.isNullOrEmpty;

import ch.threema.domain.protocol.csp.ProtocolDefines;

public class TextMessageSendAction extends SendAction {
    private static final Logger logger = getThreemaLogger("TextMessageSendAction");

    protected static volatile TextMessageSendAction instance;
    private static final Object instanceLock = new Object();

    private TextMessageSendAction() {
        // Singleton
    }

    public static TextMessageSendAction getInstance() {
        if (instance == null) {
            synchronized (instanceLock) {
                if (instance == null) {
                    instance = new TextMessageSendAction();
                }
            }
        }
        return instance;
    }

    public boolean sendTextMessage(
        final MessageReceiver[] allReceivers,
        String text,
        final ActionHandler actionHandler
    ) {

        if (actionHandler == null) {
            return false;
        }

        MessageService messageService = null;
        var serviceManager = getServiceManager();
        if (serviceManager != null) {
            messageService = serviceManager.getMessageService();
        }

        if (messageService == null || isNullOrEmpty(text)) {
            actionHandler.onError("Nothing to send");
            return false;
        }

        if (allReceivers.length < 1) {
            actionHandler.onError("No message receiver");
            return false;
        }

        /* split input text into multiple strings if necessary */
        ArrayList<String> messageTexts =
            TextUtil.splitEmojiText(text, ProtocolDefines.MAX_TEXT_MESSAGE_LEN);

        // add distribution list members to list of receivers
        final MessageReceiver[] resolvedReceivers = MessageUtil.addDistributionListReceivers(allReceivers);
        final int numReceivers = resolvedReceivers.length;

        if (numReceivers > 0) {
            actionHandler.onProgress(100, 100);
            for (MessageReceiver receiver : resolvedReceivers) {
                try {
                    for (String messageText : messageTexts) {
                        messageService.sendText(messageText, receiver);
                    }
                } catch (final Exception e) {
                    logger.error("Could not send text message", e);
                    actionHandler.onError(e.getMessage());
                    return false;
                }
            }
            actionHandler.onCompleted();
            return true;
        }
        return false;
    }
}
