package com.lemenzo.messenger;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.lemenzo.messenger.data.DraftRepository;
import com.lemenzo.messenger.model.BroadcastRecord;
import com.lemenzo.messenger.data.BroadcastStore;
import com.lemenzo.messenger.data.MessageRepository;
import com.lemenzo.messenger.data.PendingMessageStore;
import com.lemenzo.messenger.data.ContactResolver;
import com.lemenzo.messenger.mms.MmsSender;
import com.lemenzo.messenger.sms.SmsSender;
import com.lemenzo.messenger.sms.SubscriptionHelper;
import com.lemenzo.messenger.ui.Ui;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class ComposeActivity extends Activity {
    static final class Recipient {
        final long contactId;
        final String name;
        final String number;
        Recipient(long contactId, String name, String number) {
            this.contactId = contactId;
            this.name = name;
            this.number = number;
        }
    }
    private static final int REQUEST_ATTACHMENT = 2001;
    private EditText to;
    private EditText body;
    private ImageButton send;
    private DraftRepository drafts;
    private Uri pendingAttachment;
    private LinearLayout attachmentPreview;
    private TextView attachmentName;
    private ImageView attachmentThumb;
    private ContactResolver contacts;
    private String selectedAddress;
    private final LinkedHashMap<String, Recipient> selectedRecipients = new LinkedHashMap<>();
    private boolean updatingRecipient;
    private final ExecutorService ioExecutor = Executors.newSingleThreadExecutor();
    private final ExecutorService sendExecutor = Executors.newSingleThreadExecutor();
    private boolean sendInFlight;

    @Override public void onCreate(Bundle state) {
        super.onCreate(state);
        drafts = new DraftRepository(this);
        contacts = new ContactResolver(this);
        build();
        handleIntent(getIntent());
    }

    @Override protected void onDestroy() {
        ioExecutor.shutdownNow();
        sendExecutor.shutdown();
        super.onDestroy();
    }

    @Override protected void onPause() {
        super.onPause();
        if (drafts == null || body == null) return;
        String address = actualAddress();
        drafts.save(address == null || address.isEmpty() ? null : address, body.getText().toString());
    }

    private void build() {
        LinearLayout root = new LinearLayout(this);
        root.setOrientation(LinearLayout.VERTICAL);
        root.setBackgroundColor(getColor(R.color.lemenzo_background));
        int horizontal = Ui.dp(root, 18);
        root.setPadding(horizontal, Ui.dp(root, 8), horizontal, Ui.dp(root, 10));
        Ui.applyImeAwareInsets(this, root);

        LinearLayout header = new LinearLayout(this);
        header.setGravity(Gravity.CENTER_VERTICAL);
        ImageButton back = Ui.iconButton(this, R.drawable.ic_back, getString(R.string.navigate_back));
        back.setOnClickListener(v -> finish());
        header.addView(back, new LinearLayout.LayoutParams(Ui.dp(root, 48), Ui.dp(root, 54)));
        TextView title = Ui.text(this, getString(R.string.new_message), 23, true);
        header.addView(title, new LinearLayout.LayoutParams(0, Ui.dp(root, 56), 1f));
        ImageButton contact = Ui.iconButton(this, R.drawable.ic_contact_add, getString(R.string.choose_contact));
        contact.setOnClickListener(v -> pickContact());
        header.addView(contact, new LinearLayout.LayoutParams(Ui.dp(root, 48), Ui.dp(root, 48)));
        root.addView(header);

        LinearLayout recipientRow = new LinearLayout(this);
        recipientRow.setGravity(Gravity.CENTER_VERTICAL);
        recipientRow.setPadding(Ui.dp(root, 2), Ui.dp(root, 8), 0, Ui.dp(root, 10));
        TextView toLabel = Ui.text(this, getString(R.string.recipient_hint) + ":", 15, false);
        toLabel.setTextColor(getColor(R.color.lemenzo_text_secondary));
        recipientRow.addView(toLabel, new LinearLayout.LayoutParams(Ui.dp(root, 36), Ui.dp(root, 48)));

        to = new EditText(this);
        to.setSingleLine(true);
        to.setTextSize(16);
        to.setTextColor(getColor(R.color.lemenzo_text_primary));
        to.setHintTextColor(getColor(R.color.lemenzo_text_muted));
        to.setHint(R.string.recipient_name_or_number);
        to.setBackgroundColor(0x00000000);
        to.setPadding(Ui.dp(root, 6), 0, Ui.dp(root, 8), 0);
        recipientRow.addView(to, new LinearLayout.LayoutParams(0, Ui.dp(root, 48), 1f));

        ImageButton plus = Ui.iconButton(this, R.drawable.ic_add, getString(R.string.choose_contact));
        plus.setBackgroundResource(R.drawable.round_blue_button);
        plus.setPadding(Ui.dp(root, 13), Ui.dp(root, 13), Ui.dp(root, 13), Ui.dp(root, 13));
        plus.setOnClickListener(v -> pickContact());
        recipientRow.addView(plus, new LinearLayout.LayoutParams(Ui.dp(root, 48), Ui.dp(root, 48)));
        root.addView(recipientRow);

        View divider = new View(this);
        divider.setBackgroundColor(getColor(R.color.lemenzo_divider));
        root.addView(divider, new LinearLayout.LayoutParams(-1, Ui.dp(root, 1)));

        android.widget.Space space = new android.widget.Space(this);
        root.addView(space, new LinearLayout.LayoutParams(-1, 0, 1f));

        attachmentPreview = new LinearLayout(this);
        attachmentPreview.setGravity(Gravity.CENTER_VERTICAL);
        attachmentPreview.setBackgroundResource(R.drawable.card_background);
        attachmentPreview.setPadding(Ui.dp(root, 12), Ui.dp(root, 8), Ui.dp(root, 6), Ui.dp(root, 8));
        attachmentPreview.setVisibility(View.GONE);
        attachmentThumb = new ImageView(this);
        attachmentThumb.setScaleType(ImageView.ScaleType.CENTER_CROP);
        attachmentThumb.setBackgroundResource(R.drawable.circle_surface);
        attachmentThumb.setPadding(Ui.dp(root, 8), Ui.dp(root, 8), Ui.dp(root, 8), Ui.dp(root, 8));
        LinearLayout.LayoutParams thumbLp = new LinearLayout.LayoutParams(Ui.dp(root, 42), Ui.dp(root, 42));
        thumbLp.setMargins(0, 0, Ui.dp(root, 10), 0);
        attachmentPreview.addView(attachmentThumb, thumbLp);
        attachmentName = Ui.text(this, "", 13.5f, false);
        attachmentName.setTextColor(getColor(R.color.lemenzo_text_secondary));
        attachmentPreview.addView(attachmentName, new LinearLayout.LayoutParams(0, -2, 1f));
        ImageButton removeAttachment = Ui.iconButton(this, R.drawable.ic_close, getString(R.string.remove_attachment));
        removeAttachment.setOnClickListener(v -> clearAttachment());
        attachmentPreview.addView(removeAttachment, new LinearLayout.LayoutParams(Ui.dp(root, 48), Ui.dp(root, 48)));
        LinearLayout.LayoutParams ap = new LinearLayout.LayoutParams(-1, -2);ap.setMargins(0,0,0,Ui.dp(root,8));
        root.addView(attachmentPreview, ap);

        LinearLayout composerBar = new LinearLayout(this);
        composerBar.setGravity(Gravity.BOTTOM);
        composerBar.setPadding(0, Ui.dp(root, 8), 0, Ui.dp(root, 2));

        ImageButton attach = Ui.iconButton(this, R.drawable.ic_add, getString(R.string.attach));
        attach.setBackgroundResource(R.drawable.circle_surface);
        attach.setOnClickListener(v -> pickAttachment());
        LinearLayout.LayoutParams attachLp=new LinearLayout.LayoutParams(Ui.dp(root,48),Ui.dp(root,48));attachLp.gravity=Gravity.BOTTOM;
        composerBar.addView(attach, attachLp);

        LinearLayout inputShell = new LinearLayout(this);
        inputShell.setGravity(Gravity.BOTTOM);
        inputShell.setMinimumHeight(Ui.dp(root, 52));
        inputShell.setBackgroundResource(R.drawable.composer_background);
        inputShell.setPadding(Ui.dp(root, 8), Ui.dp(root, 4), Ui.dp(root, 6), Ui.dp(root, 4));
        LinearLayout.LayoutParams shellParams = new LinearLayout.LayoutParams(0, -2, 1f);
        shellParams.setMargins(Ui.dp(root, 9), 0, Ui.dp(root, 9), 0);
        composerBar.addView(inputShell, shellParams);

        body = new EditText(this);
        body.setHint(R.string.message_hint);
        body.setTextColor(getColor(R.color.lemenzo_text_primary));
        body.setHintTextColor(getColor(R.color.lemenzo_text_muted));
        body.setTextSize(SettingsActivity.messageTextSize(this));
        body.setSingleLine(false);
        body.setMaxLines(5);
        body.setMaxHeight(Ui.dp(root, 124));
        body.setMinHeight(Ui.dp(root, 44));
        body.setGravity(Gravity.CENTER_VERTICAL);
        body.setBackgroundColor(0x00000000);
        body.setPadding(Ui.dp(root, 6), 0, Ui.dp(root, 2), 0);
        inputShell.addView(body, new LinearLayout.LayoutParams(0, -2, 1f));


        send = Ui.iconButton(this, R.drawable.ic_send, getString(R.string.send_message));
        send.setBackgroundResource(R.drawable.round_blue_button);
        send.setPadding(Ui.dp(root, 14), Ui.dp(root, 14), Ui.dp(root, 14), Ui.dp(root, 14));
        send.setOnClickListener(v -> send());
        LinearLayout.LayoutParams sendLp=new LinearLayout.LayoutParams(Ui.dp(root,52),Ui.dp(root,52));sendLp.gravity=Gravity.BOTTOM;
        composerBar.addView(send, sendLp);
        root.addView(composerBar);

        to.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence s,int st,int c,int a) {}
            public void onTextChanged(CharSequence s,int st,int b,int c) {
                if(!updatingRecipient) {
                    selectedAddress=null;
                    selectedRecipients.clear();
                    to.setBackgroundColor(0x00000000);
                    to.setPadding(Ui.dp(to, 6), 0, Ui.dp(to, 8), 0);
                }
                updateSendState();
            }
            public void afterTextChanged(Editable e) {}
        });
        body.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence s,int st,int c,int a) {}
            public void onTextChanged(CharSequence s,int st,int b,int c) { updateSendState(); }
            public void afterTextChanged(Editable e) {}
        });
        updateSendState();
        setContentView(root);
    }

    private void showKeyboard(EditText field) {
        field.post(() -> {
            InputMethodManager imm = getSystemService(InputMethodManager.class);
            if (imm != null) imm.showSoftInput(field, InputMethodManager.SHOW_IMPLICIT);
        });
    }

    private String actualAddress(){
        if (selectedRecipients.size() == 1) {
            return selectedRecipients.values().iterator().next().number;
        }
        if (selectedAddress != null && !selectedAddress.trim().isEmpty()) return selectedAddress.trim();
        if (to == null) return null;
        String value = to.getText().toString().trim();
        if (value.isEmpty()) return null;
        if (contacts == null) return value;
        String resolved = contacts.resolveAddress(value);
        return resolved == null || resolved.trim().isEmpty() ? null : resolved.trim();
    }

    private void updateSendState() {
        if (send == null || to == null || body == null) return;
        String address = actualAddress();
        boolean hasRecipients = !selectedRecipients.isEmpty() || (address != null && !address.isEmpty());
        boolean contentReady = !body.getText().toString().trim().isEmpty() || pendingAttachment != null;
        boolean attachmentAllowed = pendingAttachment == null || selectedRecipients.size() <= 1;
        boolean enabled = hasRecipients && contentReady && attachmentAllowed;
        send.setEnabled(enabled);
        send.setAlpha(enabled ? 1f : 0.45f);
    }

    private void handleIntent(Intent intent) {
        Uri data = intent.getData();
        if (data != null) {
            String recipient = data.getSchemeSpecificPart();
            if (recipient != null) {
                int q = recipient.indexOf('?');
                if (q >= 0) recipient = recipient.substring(0, q);
                selectedAddress = Uri.decode(recipient);
                updatingRecipient=true;to.setText(selectedAddress);updatingRecipient=false;
            }
            String bodyQuery = null;
            if (data.isHierarchical()) {
                bodyQuery = data.getQueryParameter("body");
            } else {
                String ssp = data.getEncodedSchemeSpecificPart();
                if (ssp != null) {
                    int queryStart = ssp.indexOf('?');
                    if (queryStart >= 0 && queryStart + 1 < ssp.length()) {
                        String query = ssp.substring(queryStart + 1);
                        for (String part : query.split("&")) {
                            int equals = part.indexOf('=');
                            String key = equals >= 0 ? part.substring(0, equals) : part;
                            if ("body".equals(Uri.decode(key))) {
                                String value = equals >= 0 ? part.substring(equals + 1) : "";
                                bodyQuery = Uri.decode(value);
                                break;
                            }
                        }
                    }
                }
            }
            if (bodyQuery != null && !bodyQuery.isEmpty()) body.setText(bodyQuery);
        }
        String shared = intent.getStringExtra(Intent.EXTRA_TEXT);
        if (shared != null && !shared.isEmpty()) body.setText(shared);
        String resolved = actualAddress();
        if (body.length() == 0) body.setText(drafts.load(resolved == null || resolved.isEmpty() ? null : resolved));
        updateSendState();
    }

    private void pickAttachment() {
        Intent picker = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        picker.addCategory(Intent.CATEGORY_OPENABLE);
        picker.setType("*/*");
        picker.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{"image/*", "video/*", "audio/*", "text/x-vcard"});
        startActivityForResult(picker, REQUEST_ATTACHMENT);
    }

    private void pickContact() {
        if (checkSelfPermission(android.Manifest.permission.READ_CONTACTS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{android.Manifest.permission.READ_CONTACTS}, 3001);
            return;
        }
        showContactPickerDialog();
    }

    private static final int REQUEST_CONTACT = 3002;

    private void showContactPickerDialog() {
        if (checkSelfPermission(android.Manifest.permission.READ_CONTACTS)
                != android.content.pm.PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{android.Manifest.permission.READ_CONTACTS}, 3001);
            return;
        }
        Intent intent = new Intent(this, ContactPickerActivity.class);
        if (!selectedRecipients.isEmpty()) {
            int size = selectedRecipients.size();
            String[] names = new String[size];
            String[] numbers = new String[size];
            long[] ids = new long[size];
            int i = 0;
            for (Recipient r : selectedRecipients.values()) {
                names[i] = r.name;
                numbers[i] = r.number;
                ids[i] = r.contactId;
                i++;
            }
            intent.putExtra(ContactPickerActivity.EXTRA_PRESELECTED_NAMES, names);
            intent.putExtra(ContactPickerActivity.EXTRA_PRESELECTED_NUMBERS, numbers);
            intent.putExtra(ContactPickerActivity.EXTRA_PRESELECTED_CONTACT_IDS, ids);
        }
        startActivityForResult(intent, REQUEST_CONTACT);
    }

    @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 3001 && grantResults.length > 0
                && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
            showContactPickerDialog();
        }
    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) return;
        if (requestCode == REQUEST_CONTACT) {
            String[] numbers = data.getStringArrayExtra(ContactPickerActivity.EXTRA_NUMBERS);
            String[] names = data.getStringArrayExtra(ContactPickerActivity.EXTRA_NAMES);
            long[] ids = data.getLongArrayExtra(ContactPickerActivity.EXTRA_CONTACT_IDS);

            selectedRecipients.clear();
            if (numbers != null) {
                for (int i = 0; i < numbers.length; i++) {
                    String number = numbers[i];
                    if (number == null || number.trim().isEmpty()) continue;
                    String name = names != null && i < names.length ? names[i] : number;
                    long id = ids != null && i < ids.length ? ids[i] : -(i + 1L);
                    selectedRecipients.put(number, new Recipient(id, name, number));
                }
            } else {
                String number = data.getStringExtra(ContactPickerActivity.EXTRA_NUMBER);
                String name = data.getStringExtra(ContactPickerActivity.EXTRA_NAME);
                if (number != null && !number.trim().isEmpty()) {
                    selectedRecipients.put(number, new Recipient(-1, name, number));
                }
            }

            if (!selectedRecipients.isEmpty()) {
                selectedAddress = selectedRecipients.size() == 1
                        ? selectedRecipients.values().iterator().next().number
                        : null;
                updatingRecipient = true;
                to.setText(recipientSummary());
                to.setSelection(to.length());
                to.setBackgroundResource(R.drawable.recipient_chip);
                to.setPadding(Ui.dp(to, 12), 0, Ui.dp(to, 12), 0);
                updatingRecipient = false;
                updateSendState();
            }
            return;
        }
        if (requestCode == REQUEST_ATTACHMENT) {
            pendingAttachment = data.getData();
            if (pendingAttachment != null) {
                try { getContentResolver().takePersistableUriPermission(pendingAttachment, data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION); } catch (SecurityException ignored) {}
                showAttachmentPreview(pendingAttachment);
                updateSendState();
            }
        }
    }

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

    private void showAttachmentPreview(Uri uri){
        attachmentPreview.setVisibility(View.VISIBLE);
        attachmentName.setText(R.string.mms_attachment);
        attachmentThumb.setPadding(Ui.dp(attachmentThumb,8),Ui.dp(attachmentThumb,8),Ui.dp(attachmentThumb,8),Ui.dp(attachmentThumb,8));
        attachmentThumb.setImageResource(R.drawable.ic_attachment_file);
        attachmentThumb.setContentDescription(getString(R.string.mms_attachment));
        ioExecutor.execute(() -> {
            String label=getString(R.string.mms_attachment);
            String type=null;
            android.graphics.Bitmap thumb=null;
            try(Cursor c=getContentResolver().query(uri,new String[]{OpenableColumns.DISPLAY_NAME},null,null,null)){
                if(c!=null&&c.moveToFirst()&&c.getString(0)!=null)label=c.getString(0);
            }catch(RuntimeException ignored){}
            try { type=getContentResolver().getType(uri); } catch (RuntimeException ignored) {}
            if(type!=null&&type.startsWith("image/")){
                try { thumb=getContentResolver().loadThumbnail(uri,new android.util.Size(96,96),null); }
                catch (Exception ignored) {}
            }
            final String finalLabel=label;
            final android.graphics.Bitmap finalThumb=thumb;
            runOnUiThread(() -> {
                if (isFinishing() || isDestroyed() || pendingAttachment == null || !pendingAttachment.equals(uri)) return;
                attachmentName.setText(finalLabel);
                if(finalThumb!=null){
                    attachmentThumb.setPadding(0,0,0,0);
                    attachmentThumb.setImageBitmap(finalThumb);
                    attachmentThumb.setContentDescription(getString(R.string.attachment_image));
                }
            });
        });
    }

    private void clearAttachment(){pendingAttachment=null;if(attachmentPreview!=null)attachmentPreview.setVisibility(View.GONE);updateSendState();}

    private void send() {
        if (sendInFlight) return;
        String text = body.getText().toString().trim();

        if (selectedRecipients.size() > 1) {
            if (pendingAttachment != null) {
                android.widget.Toast.makeText(this, R.string.multi_recipient_attachments_not_supported,
                        android.widget.Toast.LENGTH_LONG).show();
                return;
            }
            if (text.isEmpty()) return;

            final ArrayList<Recipient> recipients = new ArrayList<>(selectedRecipients.values());
            SubscriptionHelper.choose(this, subscriptionId -> {
                sendInFlight = true;
                send.setEnabled(false);
                send.setAlpha(0.55f);
                to.setEnabled(false);
                body.setEnabled(false);

                sendExecutor.execute(() -> {
                    ArrayList<BroadcastRecord.Recipient> storedRecipients = new ArrayList<>();
                    for (Recipient recipient : recipients) {
                        storedRecipients.add(new BroadcastRecord.Recipient(
                                recipient.contactId, recipient.name, recipient.number, "queued"));
                    }
                    BroadcastRecord broadcast = new BroadcastStore(getApplicationContext())
                            .create(text, storedRecipients);
                    BroadcastRecord.Message initialMessage = broadcast.latestMessage();
                    final String broadcastMessageId =
                            initialMessage == null ? null : initialMessage.id;

                    int accepted = 0;
                    for (Recipient recipient : recipients) {
                        if (SmsSender.sendBroadcastRecipient(
                                getApplicationContext(), recipient.number, text,
                                subscriptionId, broadcast.id, broadcastMessageId)) {
                            accepted++;
                        } else {
                            new BroadcastStore(getApplicationContext())
                                    .updateRecipient(
                                            broadcast.id, broadcastMessageId,
                                            recipient.number, "failed");
                        }
                    }
                    final int acceptedCount = accepted;
                    final String broadcastId = broadcast.id;
                    runOnUiThread(() -> {
                        sendInFlight = false;
                        if (isFinishing() || isDestroyed()) return;
                        send.setEnabled(true);
                        send.setAlpha(1f);
                        to.setEnabled(true);
                        body.setEnabled(true);

                        if (acceptedCount > 0) {
                            drafts.clear(null);
                            body.setText("");
                            android.widget.Toast.makeText(
                                    this,
                                    getString(R.string.private_send_queued, acceptedCount, recipients.size()),
                                    android.widget.Toast.LENGTH_LONG).show();
                            Intent detail = new Intent(this, BroadcastActivity.class)
                                    .putExtra(BroadcastActivity.EXTRA_BROADCAST_ID, broadcastId)
                                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(detail);
                            finish();
                        } else {
                            android.widget.Toast.makeText(this, R.string.send_failed,
                                    android.widget.Toast.LENGTH_LONG).show();
                        }
                    });
                });
            });
            return;
        }

        String address = actualAddress();
        if (address == null || address.isEmpty()) {
            android.widget.Toast.makeText(this, R.string.recipient_not_found,
                    android.widget.Toast.LENGTH_LONG).show();
            return;
        }
        if (text.isEmpty() && pendingAttachment == null) return;
        final Uri attachment = pendingAttachment;
        SubscriptionHelper.choose(this, subscriptionId -> {
            sendInFlight = true;
            send.setEnabled(false);
            send.setAlpha(0.55f);
            sendExecutor.execute(() -> {
                boolean accepted = attachment != null
                        ? MmsSender.send(getApplicationContext(), address, text, attachment, subscriptionId)
                        : SmsSender.send(getApplicationContext(), address, text, subscriptionId);
                runOnUiThread(() -> {
                    sendInFlight = false;
                    if (isFinishing() || isDestroyed()) return;
                    send.setEnabled(true);
                    send.setAlpha(1f);
                    PendingMessageStore pendingStore = new PendingMessageStore(this);
                    boolean hasPending = pendingStore.hasForAddress(address);
                    if (accepted || hasPending) {
                        drafts.clear(address);
                        if (attachment != null && attachment.equals(pendingAttachment)) clearAttachment();
                        long threadId = new MessageRepository(this).threadIdForRecipients(address);
                        Intent conversation = new Intent(this, ConversationActivity.class)
                                .putExtra("thread_id", threadId)
                                .putExtra("address", address)
                                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(conversation);
                        finish();
                    } else {
                        android.widget.Toast.makeText(this,
                                attachment != null ? R.string.mms_send_failed : R.string.send_failed,
                                android.widget.Toast.LENGTH_LONG).show();
                    }
                });
            });
        });
    }

}