Add QS tile for Night Display when first used

Bug: 30994985
Test: runtest systemui, and manual - verify that the quick settings
panel does not have a Night Display quick settings tile, then turn
Night Display on and verify that the tile has appeared. Multiuser
does NOT work and is tracked separately.

Change-Id: I997b4ca7952016fc703a6bb777e500f4eccce189
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java
index 31cfa66..cd9a49d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java
@@ -19,6 +19,8 @@
 import android.os.Looper;
 import android.provider.Settings.Secure;
 
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.app.NightDisplayController;
 import com.android.systemui.Dependency;
 import com.android.systemui.Prefs;
 import com.android.systemui.Prefs.Key;
@@ -64,6 +66,11 @@
         if (!Prefs.getBoolean(context, Key.QS_WORK_ADDED, false)) {
             Dependency.get(ManagedProfileController.class).addCallback(mProfileCallback);
         }
+
+        if (!Prefs.getBoolean(context, Key.QS_NIGHTDISPLAY_ADDED, false)
+                && NightDisplayController.isAvailable(mContext)) {
+            Dependency.get(NightDisplayController.class).setListener(mNightDisplayCallback);
+        }
     }
 
     public void destroy() {
@@ -71,6 +78,7 @@
         Dependency.get(HotspotController.class).removeCallback(mHotspotCallback);
         Dependency.get(DataSaverController.class).removeCallback(mDataSaverListener);
         Dependency.get(ManagedProfileController.class).removeCallback(mProfileCallback);
+        Dependency.get(NightDisplayController.class).setListener(null);
     }
 
     private final ManagedProfileController.Callback mProfileCallback =
@@ -115,4 +123,30 @@
             }
         }
     };
+
+    @VisibleForTesting
+    final NightDisplayController.Callback mNightDisplayCallback =
+            new NightDisplayController.Callback() {
+        @Override
+        public void onActivated(boolean activated) {
+            if (activated) {
+                addNightTile();
+            }
+        }
+
+        @Override
+        public void onAutoModeChanged(int autoMode) {
+            if (autoMode == NightDisplayController.AUTO_MODE_CUSTOM
+                    || autoMode == NightDisplayController.AUTO_MODE_TWILIGHT) {
+                addNightTile();
+            }
+        }
+
+        private void addNightTile() {
+            mHost.addTile("night");
+            Prefs.putBoolean(mContext, Key.QS_NIGHTDISPLAY_ADDED, true);
+            mHandler.post(() -> Dependency.get(NightDisplayController.class)
+                    .setListener(null));
+        }
+    };
 }