package com.lemenzo.messenger.model;

import java.util.ArrayList;

public final class BroadcastRecord {
    public String id;
    public long date;
    public String body; // legacy/latest preview
    public String title;
    public int expectedTotal;
    public int total;
    public int sent;    // latest message aggregate
    public int failed;  // latest message aggregate
    public final ArrayList<Recipient> recipients = new ArrayList<>();
    public final ArrayList<Message> messages = new ArrayList<>();

    public static final class Recipient {
        public long contactId;
        public String name;
        public String number;
        public String state; // latest message state
        public String body;  // latest rendered body (personalized Multi SMS)

        public Recipient(long contactId, String name, String number, String state) {
            this(contactId,name,number,state,"");
        }

        public Recipient(long contactId, String name, String number, String state, String body) {
            this.contactId = contactId;
            this.name = name == null ? "" : name;
            this.number = number == null ? "" : number;
            this.state = state == null ? "queued" : state;
            this.body = body == null ? "" : body;
        }
    }

    public static final class Message {
        public String id;
        public long date;
        public String body;
        public int expectedTotal;
        public int sent;
        public int failed;
        public final ArrayList<MessageRecipient> recipients = new ArrayList<>();

        public int pending() {
            return Math.max(0, expectedTotal - sent - failed);
        }
    }

    public static final class MessageRecipient {
        public String number;
        public String name;
        public String state;
        public String renderedBody;

        public MessageRecipient(String number, String name, String state, String renderedBody) {
            this.number = number == null ? "" : number;
            this.name = name == null ? "" : name;
            this.state = state == null ? "queued" : state;
            this.renderedBody = renderedBody == null ? "" : renderedBody;
        }
    }

    public String displayName() {
        StringBuilder out = new StringBuilder();
        int shown = 0;
        for (Recipient r : recipients) {
            if (shown > 0) out.append(", ");
            String label = r.name == null || r.name.trim().isEmpty() ? r.number : r.name.trim();
            out.append(label);
            shown++;
            if (shown == 3 && recipients.size() > 3) {
                out.append(" +").append(recipients.size() - shown);
                break;
            }
        }
        return out.toString();
    }

    public Message latestMessage() {
        return messages.isEmpty() ? null : messages.get(messages.size() - 1);
    }
}
