/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * 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 com.android.keyguard;

import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
import static com.android.internal.widget.LockDomain.Secondary;
import static com.android.systemui.flags.Flags.LOCKSCREEN_ENABLE_LANDSCAPE;

import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;

import androidx.asynclayoutinflater.view.AsyncLayoutInflater;

import com.android.internal.annotations.VisibleForTesting;
import com.android.keyguard.KeyguardInputViewController.Factory;
import com.android.keyguard.KeyguardSecurityModel.SecurityMode;
import com.android.keyguard.dagger.KeyguardBouncerScope;
import com.android.systemui.flags.FeatureFlags;
import com.android.systemui.res.R;
import com.android.systemui.util.ViewController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * Controller for a {@link KeyguardSecurityViewFlipper}.
 */
@KeyguardBouncerScope
public class KeyguardSecurityViewFlipperController
        extends ViewController<KeyguardSecurityViewFlipper> {

    private static final boolean DEBUG = KeyguardConstants.DEBUG;
    private static final String TAG = "KeyguardSecurityView";

    private final List<KeyguardInputViewController<KeyguardInputView>> mChildren =
            new ArrayList<>();
    private final LayoutInflater mLayoutInflater;
    private final AsyncLayoutInflater mAsyncLayoutInflater;
    private final EmergencyButtonController.Factory mEmergencyButtonControllerFactory;
    private final Factory mKeyguardSecurityViewControllerFactory;
    private final FeatureFlags mFeatureFlags;

    private KeyguardSecurityViewFlipperController.OnViewInflatedCallback
            mBouncerBindMessageViewCallback;
    // Because we now have multiple security modes, it can happen that #getSecurityView gets called
    // consecutively and issues multiple inflation requests for the same view. We prevent this
    // from happening by preloading security modes in KSCC#reinflateViewFlipper, but this map
    // provides us with additional assurance that there are no race conditions and also gives us the
    // option to avoid/reduce preloading if it becomes necessary.
    private final Map<SecurityMode, List<OnViewInflatedCallback>> mOnViewInflatedListeners =
            new HashMap<>();
    // This counter allows us to discard views that are being async inflated when #clearViews is
    // called.
    private int mClearCounter = 0;

    @Inject
    protected KeyguardSecurityViewFlipperController(KeyguardSecurityViewFlipper view,
            LayoutInflater layoutInflater,
            AsyncLayoutInflater asyncLayoutInflater,
            KeyguardInputViewController.Factory keyguardSecurityViewControllerFactory,
            EmergencyButtonController.Factory emergencyButtonControllerFactory,
            FeatureFlags featureFlags) {
        super(view);
        mKeyguardSecurityViewControllerFactory = keyguardSecurityViewControllerFactory;
        mLayoutInflater = layoutInflater;
        mEmergencyButtonControllerFactory = emergencyButtonControllerFactory;
        mAsyncLayoutInflater = asyncLayoutInflater;
        mFeatureFlags = featureFlags;
    }

    @Override
    protected void onViewAttached() {

    }

    @Override
    protected void onViewDetached() {

    }

    protected void setBouncerBindMessageViewCallback(
            KeyguardSecurityViewFlipperController.OnViewInflatedCallback callback) {
        mBouncerBindMessageViewCallback = callback;
    }

    public void reset() {
        for (KeyguardInputViewController<KeyguardInputView> child : mChildren) {
            child.reset();
        }
    }

    /** Handles density or font scale changes. */
    public void clearViews() {
        mOnViewInflatedListeners.clear();
        mClearCounter += 1;
        mView.removeAllViews();
        mChildren.clear();
    }

    void getSecurityView(SecurityMode securityMode,
            KeyguardSecurityCallback keyguardSecurityCallback,
            OnViewInflatedCallback onViewInflatedCallback) {
        if (!Looper.getMainLooper().isCurrentThread()) {
            throw new IllegalStateException(
                    "KeyguardSecurityViewFlipperController#getSecurityView must be called from main"
                            + " thread");
        }

        for (KeyguardInputViewController<KeyguardInputView> child : mChildren) {
            if (child.getSecurityMode() == securityMode) {
                onViewInflatedCallback.onViewInflated(child);
                return;
            }
        }

        // Prevent multiple inflations for the same security mode. Instead, add callback to a list
        // and then notify each in order when the view is inflated.
        if (mOnViewInflatedListeners.containsKey(securityMode)) {
            List<OnViewInflatedCallback> callbacks = mOnViewInflatedListeners.get(securityMode);
            callbacks.addLast(onViewInflatedCallback);
        } else {
            mOnViewInflatedListeners.put(securityMode, new ArrayList<>(
                    Collections.singletonList(onViewInflatedCallback)));
            asynchronouslyInflateView(securityMode, keyguardSecurityCallback);
        }
    }

    /**
     * Asynchronously inflate view and then add it to view flipper on the main thread when complete.
     *
     * OnInflateFinishedListener will be called on the main thread.
     *
     * @param securityMode
     * @param keyguardSecurityCallback
     */
    private void asynchronouslyInflateView(SecurityMode securityMode,
            KeyguardSecurityCallback keyguardSecurityCallback) {
        int layoutId = mFeatureFlags.isEnabled(LOCKSCREEN_ENABLE_LANDSCAPE)
                ? getLayoutIdFor(securityMode) : getLegacyLayoutIdFor(securityMode);
        if (layoutId != 0) {
            if (DEBUG) {
                Log.v(TAG, "inflating on bg thread id = " + layoutId + " .");
            }
            int clearCounterPreInflate = mClearCounter;
            mAsyncLayoutInflater.inflate(layoutId, mView,
                    (view, resId, parent) -> {
                        // Without this, #clearViews would not clear views that are being async
                        // inflated. This fixes an upstream bug that is noticeable downstream when
                        // switching profiles as we async inflate multiple security modes in
                        // advance.
                        if (clearCounterPreInflate != mClearCounter) {
                            return;
                        }
                        if (securityMode == SecurityMode.BiometricSecondFactorPin) {
                            ((KeyguardPINView) view).setLockDomain(Secondary);
                            // By default, view ID is set to R.id.keyguard_pin_view for both regular
                            // and BSF PIN layouts.
                            // Use a distinct ID to prevent rest of the code from breaking due to
                            // duplicate IDs.
                            //
                            // 0x8000_0000 ID is outside the range of automatically defined view ID constants.
                            view.setId(0x8000_0000);
                        }

                        mView.addView(view);
                        KeyguardInputViewController<KeyguardInputView> childController =
                                mKeyguardSecurityViewControllerFactory.create(
                                        (KeyguardInputView) view,
                                        securityMode, keyguardSecurityCallback);
                        childController.init();
                        mChildren.add(childController);

                        List<OnViewInflatedCallback> callbacks = mOnViewInflatedListeners.get(
                                securityMode);
                        for (OnViewInflatedCallback callback : callbacks) {
                            callback.onViewInflated(childController);
                        }

                        // Single bouncer constrains are default
                        if (mFeatureFlags.isEnabled(LOCKSCREEN_ENABLE_LANDSCAPE)) {
                            boolean useSplitBouncer =
                                    getResources().getBoolean(R.bool.update_bouncer_constraints)
                                        && getResources().getConfiguration().orientation
                                            == ORIENTATION_LANDSCAPE;
                            updateConstraints(useSplitBouncer);
                        }

                        if (mBouncerBindMessageViewCallback != null) {
                            mBouncerBindMessageViewCallback.onViewInflated(childController);
                        }
                    });
        }
    }

    private int getLayoutIdFor(SecurityMode securityMode) {
        // TODO (b/297863911, b/297864907) - implement motion layout for other bouncers
        return switch (securityMode) {
            case SecureLockDeviceBiometricAuth ->
                    R.layout.keyguard_secure_lock_device_biometric_auth_view;
            case Pattern -> R.layout.keyguard_pattern_motion_layout;
            case PIN, BiometricSecondFactorPin -> R.layout.keyguard_pin_motion_layout;
            case Password -> R.layout.keyguard_password_motion_layout;
            case SimPin -> R.layout.keyguard_sim_pin_view;
            case SimPuk -> R.layout.keyguard_sim_puk_view;
            default -> 0;
        };
    }

    private int getLegacyLayoutIdFor(SecurityMode securityMode) {
        return switch (securityMode) {
            case SecureLockDeviceBiometricAuth ->
                    R.layout.keyguard_secure_lock_device_biometric_auth_view;
            case Pattern -> R.layout.keyguard_pattern_view;
            case PIN, BiometricSecondFactorPin -> R.layout.keyguard_pin_view;
            case Password -> R.layout.keyguard_password_view;
            case SimPin -> R.layout.keyguard_sim_pin_view;
            case SimPuk -> R.layout.keyguard_sim_puk_view;
            default -> 0;
        };
    }

    /** Updates the keyguard view's constraints (single or split constraints).
     *  Split constraints are only used for small landscape screens.
     *  Only called when flag LANDSCAPE_ENABLE_LOCKSCREEN is enabled. */
    public void updateConstraints(boolean useSplitBouncer) {
        mView.updateConstraints(useSplitBouncer);
    }

    /** Makes the supplied child visible if it is contained win this view, */
    public void show(KeyguardInputViewController<KeyguardInputView> childController) {
        int index = childController.getIndexIn(mView);
        if (index != -1) {
            mView.setDisplayedChild(index);
        }
    }

    /** Listener to when view has finished inflation. */
    public interface OnViewInflatedCallback {
        /** Notifies that view has been inflated */
        void onViewInflated(KeyguardInputViewController<KeyguardInputView> controller);
    }
}
