package com.mobify.astro.helpers;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.function.Predicate;

import static junit.framework.Assert.assertNotNull;

public class AstroViewAsserts {
    private AstroViewAsserts() {}

    public static void assertViewHasDescendantWithText(View view, final String text) {
        View viewWithTest = findInViewTree(view, new Predicate<View>() {
            @Override
            public boolean test(View view) {
                if (view instanceof TextView) {
                    TextView tv = (TextView)view;
                    return (tv.getText().equals(text));
                }
                return false;
            }
        });

        assertNotNull(viewWithTest);
    }

    public static void assertViewHasDescendantWithPopulatedImageView(View view) {
        assertViewHasDescendant(view, new Predicate<View>() {
            @Override
            public boolean test(View view) {
                if (view instanceof ImageView) {
                    ImageView imageView = (ImageView) view;
                    return (imageView.getDrawable() != null);
                }
                return false;
            }
        });
    }

    public static void assertViewHasDescendantView(View parent, final View descendant) {
        assertViewHasDescendant(parent, new Predicate<View>() {
            @Override
            public boolean test(View view) {
                return view == descendant;
            }
        });
    }

    public static void assertViewHasDescendant(View view, Predicate<View> predicate) {
        View matchingView = findInViewTree(view, predicate);
        assertNotNull(matchingView);
    }

    private static View findInViewTree(View parent, Predicate<View> predicate) {
        if (predicate.test(parent)) {
            return parent;
        }

        if (parent instanceof ViewGroup) {
            ViewGroup parentGroup = (ViewGroup) parent;
            for (int i = 0; i < parentGroup.getChildCount(); i++) {
                View match = findInViewTree(parentGroup.getChildAt(i), predicate);
                if (match != null) {
                    return match;
                }
            }
        }

        return null;
    }
}
