package ir.asparsa.android.core.util;

import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import ir.asparsa.android.core.logger.L;
import ir.asparsa.android.ui.fragment.BaseFragment;

import java.util.List;

/**
 * @author hadi
 * @since 3/12/2017 AD.
 */
public class UiUtil {

    public static void invokeEventReceiver(
            @NonNull BaseFragment.BaseEvent event,
            @NonNull FragmentManager fragmentManager
    ) {
        invokeEventReceiver(event, fragmentManager, false);
    }


    public static void invokeEventReceiver(
            @NonNull BaseFragment.BaseEvent event,
            @NonNull FragmentManager fragmentManager,
            boolean popBackStack
    ) {
        List<Fragment> fragments = fragmentManager.getFragments();
        for (int i = fragments.size() - 1; i >= 0; i--) {
            Fragment fragment = fragments.get(i);
            if (fragment instanceof BaseFragment &&
                event.getSourceTag().equals(((BaseFragment) fragment).getTagName())) {
                L.i(UiUtil.class, "Find base fragment to send event: " + fragment.getClass().getName());
                ((BaseFragment) fragment).onEvent(event);
                break;
            } else if (popBackStack && fragment != null) {
                try {
                    fragmentManager.popBackStack(fragment.getTag(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
                } catch (Exception e) {
                    L.e(UiUtil.class.getClass(), "Back problem!", e);
                }
            }
        }
    }

}

@@ -260,32 +260,8 @@
 t;%0A%0A
-import java.util.List;%0A%0A
 /**%0A
@@ -753,32 +753,18 @@
     
-List%3CFragment%3E fragments
+for (int i
  = f
@@ -785,126 +785,230 @@
 .get
-Fragme
+BackStackEntryCou
 nt
-s
 ()
-;%0A        for (int i = fragments.size() - 1; i %3E= 0; i--) %7B%0A            Fragment fragment = fragments.get(i
+ - 1; i %3E= 0; i--) %7B%0A            FragmentManager.BackStackEntry backStack = fragmentManager.getBackStackEntryAt(i);%0A            Fragment fragment = fragmentManager.findFragmentByTag(backStack.getName()
 );%0A 

Fix bug on poping fragments for sending events through back stack