/** Cleanup when the activity is destroyed. */
 @Override
 public void onDestroy() {
   super.onDestroy();
   mActiveListItemAdapter.cleanup();
   mCurrentListRef.removeEventListener(mCurrentListRefListener);
   mCurrentUserRef.removeEventListener(mCurrentUserRefListener);
   mSharedWithRef.removeEventListener(mSharedWithListener);
 }
  @Override
  protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_active_list_details);

    /* Get the push ID from the extra passed by ShoppingListFragment */
    Intent intent = this.getIntent();
    mListId = intent.getStringExtra(Constants.KEY_LIST_ID);
    if (mListId == null) {
      /* No point in continuing without a valid ID. */
      finish();
      return;
    }

    /** Create Firebase references */
    mCurrentListRef =
        new Firebase(Constants.FIREBASE_URL_USER_LISTS).child(mEncodedEmail).child(mListId);
    mCurrentUserRef = new Firebase(Constants.FIREBASE_URL_USERS).child(mEncodedEmail);
    mSharedWithRef = new Firebase(Constants.FIREBASE_URL_LISTS_SHARED_WITH).child(mListId);
    Firebase listItemsRef = new Firebase(Constants.FIREBASE_URL_SHOPPING_LIST_ITEMS).child(mListId);

    /** Link layout elements from XML and setup the toolbar */
    initializeScreen();

    /** Setup the adapter */
    mActiveListItemAdapter =
        new ActiveListItemAdapter(
            this,
            ShoppingListItem.class,
            R.layout.single_active_list_item,
            listItemsRef.orderByChild(Constants.FIREBASE_PROPERTY_BOUGHT_BY),
            mListId,
            mEncodedEmail);
    /* Create ActiveListItemAdapter and set to listView */
    mListView.setAdapter(mActiveListItemAdapter);

    /**
     * Add ValueEventListeners to Firebase references to control get data and control behavior and
     * visibility of elements
     */

    /* Save the most up-to-date version of current user in mCurrentUser */
    mCurrentUserRefListener =
        mCurrentUserRef.addValueEventListener(
            new ValueEventListener() {
              @Override
              public void onDataChange(DataSnapshot dataSnapshot) {
                User currentUser = dataSnapshot.getValue(User.class);
                if (currentUser != null) mCurrentUser = currentUser;
                else finish();
              }

              @Override
              public void onCancelled(FirebaseError firebaseError) {
                Log.e(
                    LOG_TAG,
                    getString(R.string.log_error_the_read_failed) + firebaseError.getMessage());
              }
            });

    final Activity thisActivity = this;

    /**
     * Save the most recent version of current shopping list into mShoppingList instance variable an
     * update the UI to match the current list.
     */
    mCurrentListRefListener =
        mCurrentListRef.addValueEventListener(
            new ValueEventListener() {

              @Override
              public void onDataChange(DataSnapshot snapshot) {

                /**
                 * Saving the most recent version of current shopping list into mShoppingList if
                 * present finish() the activity if the list is null (list was removed or unshared
                 * by it's owner while current user is in the list details activity)
                 */
                ShoppingList shoppingList = snapshot.getValue(ShoppingList.class);

                if (shoppingList == null) {
                  finish();
                  /**
                   * Make sure to call return, otherwise the rest of the method will execute, even
                   * after calling finish.
                   */
                  return;
                }
                mShoppingList = shoppingList;
                /**
                 * Pass the shopping list to the adapter if it is not null. We do this here because
                 * mShoppingList is null when first created.
                 */
                mActiveListItemAdapter.setShoppingList(mShoppingList);

                /* Check if the current user is owner */
                mCurrentUserIsOwner = Utils.checkIfOwner(shoppingList, mEncodedEmail);

                /* Calling invalidateOptionsMenu causes onCreateOptionsMenu to be called */
                invalidateOptionsMenu();

                /* Set title appropriately. */
                setTitle(shoppingList.getListName());

                HashMap<String, User> usersShopping = mShoppingList.getUsersShopping();
                if (usersShopping != null
                    && usersShopping.size() != 0
                    && usersShopping.containsKey(mEncodedEmail)) {
                  mShopping = true;
                  mButtonShopping.setText(getString(R.string.button_stop_shopping));
                  mButtonShopping.setBackgroundColor(
                      ContextCompat.getColor(ActiveListDetailsActivity.this, R.color.dark_grey));
                } else {
                  mButtonShopping.setText(getString(R.string.button_start_shopping));
                  mButtonShopping.setBackgroundColor(
                      ContextCompat.getColor(ActiveListDetailsActivity.this, R.color.primary_dark));
                  mShopping = false;
                }

                setWhosShoppingText(mShoppingList.getUsersShopping());
              }

              @Override
              public void onCancelled(FirebaseError firebaseError) {
                Log.e(
                    LOG_TAG,
                    getString(R.string.log_error_the_read_failed) + firebaseError.getMessage());
              }
            });

    mSharedWithListener =
        mSharedWithRef.addValueEventListener(
            new ValueEventListener() {
              @Override
              public void onDataChange(DataSnapshot dataSnapshot) {
                mSharedWithUsers = new HashMap<String, User>();
                for (DataSnapshot currentUser : dataSnapshot.getChildren()) {
                  mSharedWithUsers.put(currentUser.getKey(), currentUser.getValue(User.class));
                }
                mActiveListItemAdapter.setSharedWithUsers(mSharedWithUsers);
              }

              @Override
              public void onCancelled(FirebaseError firebaseError) {
                Log.e(
                    LOG_TAG,
                    getString(R.string.log_error_the_read_failed) + firebaseError.getMessage());
              }
            });

    /** Set up click listeners for interaction. */

    /* Show edit list item name dialog on listView item long click event */
    mListView.setOnItemLongClickListener(
        new AdapterView.OnItemLongClickListener() {

          @Override
          public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            /* Check that the view is not the empty footer item */
            if (view.getId() != R.id.list_view_footer_empty) {
              ShoppingListItem shoppingListItem = mActiveListItemAdapter.getItem(position);

              if (shoppingListItem != null) {
                /*
                If the person is the owner and not shopping and the item is not bought, then
                they can edit it.
                 */
                if (shoppingListItem.getOwner().equals(mEncodedEmail)
                    && !mShopping
                    && !shoppingListItem.isBought()) {
                  String itemName = shoppingListItem.getItemName();
                  String itemId = mActiveListItemAdapter.getRef(position).getKey();
                  showEditListItemNameDialog(itemName, itemId);
                  return true;
                }
              }
            }
            return false;
          }
        });

    /* Perform buy/return action on listView item click event if current user is shopping. */
    mListView.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            /* Check that the view is not the empty footer item */
            if (view.getId() != R.id.list_view_footer_empty) {
              final ShoppingListItem selectedListItem = mActiveListItemAdapter.getItem(position);
              String itemId = mActiveListItemAdapter.getRef(position).getKey();

              if (selectedListItem != null) {
                /* If current user is shopping */
                if (mShopping) {

                  /* Create map and fill it in with deep path multi write operations list */
                  HashMap<String, Object> updatedItemBoughtData = new HashMap<String, Object>();

                  /* Buy selected item if it is NOT already bought */
                  if (!selectedListItem.isBought()) {
                    updatedItemBoughtData.put(Constants.FIREBASE_PROPERTY_BOUGHT, true);
                    updatedItemBoughtData.put(Constants.FIREBASE_PROPERTY_BOUGHT_BY, mEncodedEmail);
                  } else {
                    /* Return selected item only if it was bought by current user */
                    if (selectedListItem.getBoughtBy().equals(mEncodedEmail)) {
                      updatedItemBoughtData.put(Constants.FIREBASE_PROPERTY_BOUGHT, false);
                      updatedItemBoughtData.put(Constants.FIREBASE_PROPERTY_BOUGHT_BY, null);
                    }
                  }

                  /* Do update */
                  Firebase firebaseItemLocation =
                      new Firebase(Constants.FIREBASE_URL_SHOPPING_LIST_ITEMS)
                          .child(mListId)
                          .child(itemId);
                  firebaseItemLocation.updateChildren(
                      updatedItemBoughtData,
                      new Firebase.CompletionListener() {
                        @Override
                        public void onComplete(FirebaseError firebaseError, Firebase firebase) {
                          if (firebaseError != null) {
                            Log.d(
                                LOG_TAG,
                                getString(R.string.log_error_updating_data)
                                    + firebaseError.getMessage());
                          }
                        }
                      });
                }
              }
            }
          }
        });
  }