/*
 * Copyright 2018 Realm Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.realm.examples.arch.utils;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;

/**
 * This is a helper class to look up an Activity inside a View's context chain in a reliable/safe manner.
 */
public class ContextUtils {
    private ContextUtils() {
    }

    /**
     * Finds the Activity inside the hierarchy of the provided Context.
     *
     * @param context the context
     * @param <T> the expected type of the Activity
     * @return the activity
     *
     * @throws IllegalArgumentException if the context has no Activity in its base context hierarchy
     */
    public static <T extends Activity> T findActivity(Context context) {
        if (context instanceof Activity) {
            //noinspection unchecked
            return (T) context;
        }
        while (context != null && context instanceof ContextWrapper) {
            context = ((ContextWrapper) context).getBaseContext();
            if (context instanceof Activity) {
                //noinspection unchecked
                return (T) context;
            }
        }
        throw new IllegalArgumentException("No activity found in context hierarchy.");
    }
}
