/*
 * Copyright 2013 Urban Airship and Contributors
 */

package com.urbanairship.richpush.sample.inbox;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.PopupMenu;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.urbanairship.Logger;
import com.urbanairship.richpush.RichPushMessage;
import com.urbanairship.richpush.sample.R;
import com.urbanairship.richpush.sample.RichNotificationBuilder;

import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * Implementation of the AbstractInboxFragment that supports an action mode
 */
public class InboxFragment extends AbstractInboxFragment implements ActionMode.Callback {

    private final static long ONE_DAY_MS = 24 * 60 * 60 * 1000;

    private ActionMode actionMode;
    private Button actionSelectionButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.inbox_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.refresh) {
            this.refreshMessages();
            return true;
        }
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
        startActionModeIfNecessary();

        // Dismiss any notifications if available
        RichNotificationBuilder.dismissInboxNotification();
    }

    @Override
    public int getRowLayoutId() {
        return R.layout.inbox_list_item;
    }

    @Override
    public int getEmptyListStringId() {
        return R.string.no_messages;
    }

    private String getMessageDate(Date date) {
        long age = System.currentTimeMillis() - date.getTime();

        // Only show the date if older then 1 day
        if (age > ONE_DAY_MS) {
            return DateFormat.getDateFormat(getActivity()).format(date);
        }

        return DateFormat.getTimeFormat(getActivity()).format(date);
    }

    public void bindView(final View view, final RichPushMessage message, final int position) {
        View unreadIndicator = view.findViewById(R.id.unread_indicator);
        TextView title = (TextView) view.findViewById(R.id.title);
        TextView timeStamp = (TextView) view.findViewById(R.id.date_sent);
        final CheckBox checkBox = (CheckBox) view.findViewById(R.id.message_checkbox);

        if (message.isRead()) {
            unreadIndicator.setBackgroundColor(Color.BLACK);
            unreadIndicator.setContentDescription("Message is read");
        } else {
            unreadIndicator.setBackgroundColor(Color.YELLOW);
            unreadIndicator.setContentDescription("Message is unread");
        }

        title.setText(message.getTitle());
        timeStamp.setText(getMessageDate(message.getSentDate()));

        checkBox.setChecked(isMessageSelected(message.getMessageId()));

        checkBox.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                onMessageSelected(message.getMessageId(), checkBox.isChecked());
            }
        });
        view.setFocusable(false);
        view.setFocusableInTouchMode(false);
    }

    @Override
    public void clearSelection() {
        super.clearSelection();
        if (actionMode != null) {
            actionMode.finish();
        }
    }

    /**
     * Starts the action mode if there are any selected
     * messages in the inbox fragment
     */
    private void startActionModeIfNecessary() {
        List<String> checkedIds = getSelectedMessages();
        if (actionMode != null && checkedIds.isEmpty()) {
            actionMode.finish();
        } else if (actionMode == null && !checkedIds.isEmpty()) {
            actionMode = ((ActionBarActivity) this.getActivity()).startSupportActionMode(this);
        }
    }

    @Override
    protected void onMessageSelected(String messageId, boolean isChecked) {
        super.onMessageSelected(messageId, isChecked);
        startActionModeIfNecessary();

        if (actionMode != null) {
            actionMode.invalidate();
        }
    }

    @Override
    public void onListItemClick(ListView list, View view, int position, long id) {
        super.onListItemClick(list, view, position, id);
        // If we are in actionMode, update the menu items
        if (actionMode != null) {
            actionMode.invalidate();
        }
    }

    public ActionMode getActionMode() {
        return actionMode;
    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        mode.getMenuInflater().inflate(R.menu.inbox_actions_menu, menu);

        View customView = LayoutInflater.from(this.getActivity()).inflate(R.layout.cab_selection_dropdown, null);
        actionSelectionButton = (Button) customView.findViewById(R.id.selection_button);

        final PopupMenu popupMenu = new PopupMenu(this.getActivity(), customView);
        popupMenu.getMenuInflater().inflate(R.menu.selection, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.menu_deselect_all) {
                    clearSelection();
                } else {
                    selectAll();
                }
                return true;
            }
        });

        actionSelectionButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Menu menu = popupMenu.getMenu();
                menu.findItem(R.id.menu_deselect_all).setVisible(true);
                menu.findItem(R.id.menu_select_all).setVisible(getSelectedMessages().size() != getMessages().size());
                popupMenu.show();
            }

        });


        mode.setCustomView(customView);

        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        Logger.debug("onPrepareActionMode");

        boolean selectionContainsRead = false;
        boolean selectionContainsUnread = false;

        for (String id : getSelectedMessages()) {
            RichPushMessage message = getRichPushInbox().getMessage(id);
            if (message.isRead()) {
                selectionContainsRead = true;
            } else {
                selectionContainsUnread = true;
            }

            if (selectionContainsRead && selectionContainsUnread) {
                break;
            }
        }

        // Show them both
        menu.findItem(R.id.mark_read).setVisible(selectionContainsUnread);
        menu.findItem(R.id.mark_unread).setVisible(selectionContainsRead);

        // If we have an action selection_popup button update the text
        if (actionSelectionButton != null) {
            String selectionText = this.getString(R.string.cab_selection, getSelectedMessages().size());
            actionSelectionButton.setText(selectionText);
        }

        return true;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        Logger.debug("onActionItemClicked");
        switch (item.getItemId()) {
            case R.id.mark_read:
                getRichPushInbox().markMessagesRead(new HashSet<String>(getSelectedMessages()));
                break;
            case R.id.mark_unread:
                getRichPushInbox().markMessagesUnread(new HashSet<String>(getSelectedMessages()));
                break;
            case R.id.delete:
                getRichPushInbox().deleteMessages(new HashSet<String>(getSelectedMessages()));
                break;
            default:
                return false;
        }

        actionMode.finish();
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        Logger.debug("onDestroyActionMode");
        if (actionMode != null) {
            actionMode = null;
            clearSelection();
        }
    }

    public void onUpdateInbox() {
        super.onUpdateInbox();
        if (actionMode != null) {
            actionMode.invalidate();
        }
    }
}

@@ -7194,14 +7194,68 @@
  the
-m both
+ mark read action if any of the selected messages are unread
 %0A   
@@ -7322,24 +7322,113 @@
 insUnread);%0A
+        %0A        // Show the mark unread action if any of the selected messages are read%0A
         menu

Update InboxFragment.java