/*
 * Copyright 2018 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 androidx.textclassifier;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;

import androidx.annotation.GuardedBy;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.annotation.VisibleForTesting;
import androidx.core.util.Preconditions;

import java.util.WeakHashMap;

/**
 * Class to handle the creation of {@link TextClassifier}.
 */
public final class TextClassificationManager {
    private static final Object sLock = new Object();
    @GuardedBy("sLock")
    private static final WeakHashMap<Context, TextClassificationManager> sMapping =
            new WeakHashMap<>();

    private final Context mContext;
    private final Object mLock = new Object();
    @GuardedBy("mLock")
    private TextClassifier mTextClassifier;
    private final TextClassifier mDefaultTextClassifier;

    /** @hide **/
    @RestrictTo(RestrictTo.Scope.LIBRARY)
    @VisibleForTesting
    @SuppressLint("RestrictedApi")
    TextClassificationManager(@NonNull Context context) {
        mContext = Preconditions.checkNotNull(context);
        mDefaultTextClassifier = defaultTextClassifier(context);
    }

    /**
     * Returns an instance of {@link TextClassificationManager} for the specified context.
     * Each context has its own {@link TextClassificationManager}.
     */
    @SuppressLint("RestrictedApi")
    public static TextClassificationManager of(@NonNull Context context) {
        Preconditions.checkNotNull(context);
        synchronized (sLock) {
            TextClassificationManager textClassificationManager = sMapping.get(context);
            if (textClassificationManager == null) {
                textClassificationManager = new TextClassificationManager(context);
                sMapping.put(context, textClassificationManager);
            }
            return textClassificationManager;
        }
    }

    /**
     * Returns the text classifier set through {@link #setTextClassifier(TextClassifier)},
     * a default text classifier is returned if it is not ever set, or a {@code null} is set.
     * <p>
     * If you are implementing a text classifier, and want to delegate requests to the default
     * text classifier provided by this library, you may want to use
     * {@link #getDefaultTextClassifier()} instead.
     *
     * @see #getDefaultTextClassifier()
     */
    @NonNull
    public TextClassifier getTextClassifier() {
        synchronized (mLock) {
            if (mTextClassifier != null) {
                return mTextClassifier;
            }
        }
        return mDefaultTextClassifier;
    }

    /**
     * Sets a preferred text classifier.
     * <p>
     * To turn off the feature completely, you can set a {@link TextClassifier#NO_OP}. If
     * {@code null} is set, default text classifier is used.
     * <p>
     * Note that the given text classifier is only set to this instance of the
     * {@link TextClassificationManager}.
     */
    public void setTextClassifier(@Nullable TextClassifier textClassifier) {
        synchronized (mLock) {
            mTextClassifier = textClassifier;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                setPlatformTextClassifier(textClassifier);
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setPlatformTextClassifier(@Nullable TextClassifier textClassifier) {
        android.view.textclassifier.TextClassificationManager textClassificationManager =
                (android.view.textclassifier.TextClassificationManager)
                        mContext.getSystemService(Context.TEXT_CLASSIFICATION_SERVICE);
        if (textClassificationManager == null) {
            return;
        }
        android.view.textclassifier.TextClassifier platformTextClassifier =
                textClassifier == null
                        ? null
                        : new PlatformTextClassifier(mContext, textClassifier);
        textClassificationManager.setTextClassifier(platformTextClassifier);
    }

    /**
     * Returns the default text classifier.
     */
    private static TextClassifier defaultTextClassifier(@NonNull Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return PlatformTextClassifierWrapper.create(context);
        }
        return LegacyTextClassifier.of(context);
    }

    /**
     * Returns the default text classifier provided by this library.
     * <p>
     * This is mainly for text classifier implementation to delegate the request to the default
     * text classifier. Otherwise, in most cases, you shuold consider
     * {@link #getTextClassifier()} instead.
     * <p>
     * Note that the returned text classifier should be only used within the same context that is
     * passed to {@link TextClassificationManager#of(Context)}.
     *
     * @see #getTextClassifier()
     */
    @NonNull
    public TextClassifier getDefaultTextClassifier() {
        return mDefaultTextClassifier;
    }
}

@@ -1020,16 +1020,52 @@
 tions;%0A%0A
+import java.lang.ref.WeakReference;%0A
 import j
@@ -1247,32 +1247,127 @@
 = new Object();%0A
+    // The value has to be wrapped by a WeakReference as it is holding a reference to the key.%0A
     @GuardedBy(%22
@@ -1420,16 +1420,30 @@
 ontext, 
+WeakReference%3C
 TextClas
@@ -1460,16 +1460,17 @@
 Manager%3E
+%3E
  sMappin
@@ -2341,32 +2341,100 @@
 tNull(context);%0A
+        TextClassificationManager textClassificationManager = null;%0A
         synchron
@@ -2452,32 +2452,46 @@
 ) %7B%0A            
+WeakReference%3C
 TextClassificati
@@ -2491,32 +2491,33 @@
 ificationManager
+%3E
  textClassificat
@@ -2526,18 +2526,51 @@
 nManager
+WeakReference =%0A                  
  
-=
  sMappin
@@ -2577,32 +2577,202 @@
 g.get(context);%0A
+            if (textClassificationManagerWeakReference != null) %7B%0A                textClassificationManager = textClassificationManagerWeakReference.get();%0A            %7D%0A
             if (
@@ -2922,32 +2922,52 @@
 ng.put(context, 
+new WeakReference%3C%3E(
 textClassificati
@@ -2976,16 +2976,17 @@
 Manager)
+)
 ;%0A      
@@ -2996,29 +2996,35 @@
    %7D%0A       
+ 
+%7D%0A
      
+   
 return textC
@@ -3045,26 +3045,16 @@
 anager;%0A
-        %7D%0A
     %7D%0A%0A 

Fix a memory leak issue in AndroidX TextClassificationManager