/*
 * Copyright (C) 2014 The Android Open Source Project
 * modified
 * SPDX-License-Identifier: Apache-2.0 AND GPL-3.0-only
 */

package helium314.keyboard.latin.settings;

import android.app.Activity;
import android.app.backup.BackupManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Build;
import android.os.Bundle;
import helium314.keyboard.latin.utils.Log;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceScreen;

/**
 * A base abstract class for a {@link PreferenceFragmentCompat} that implements a nested
 * {@link PreferenceScreen} of the main preference screen.
 */
public abstract class SubScreenFragment extends PreferenceFragmentCompat
        implements OnSharedPreferenceChangeListener {
    private OnSharedPreferenceChangeListener mSharedPreferenceChangeListener;

    static void setPreferenceVisible(final String prefKey, final boolean visible,
                                     final PreferenceScreen screen) {
        final Preference preference = screen.findPreference(prefKey);
        if (preference != null) {
            preference.setVisible(visible);
        }
    }

    static void removePreference(final String prefKey, final PreferenceScreen screen) {
        final Preference preference = screen.findPreference(prefKey);
        if (preference != null && !screen.removePreference(preference)) {
            final int count = screen.getPreferenceCount();
            for (int i = 0; i < count; i++) {
                final Preference pref = screen.getPreference(i);
                if (pref instanceof PreferenceCategory
                        && ((PreferenceCategory) pref).removePreference(preference))
                    break;
            }
        }
    }

    final void setPreferenceVisible(final String prefKey, final boolean visible) {
        setPreferenceVisible(prefKey, visible, getPreferenceScreen());
    }

    final void removePreference(final String prefKey) {
        removePreference(prefKey, getPreferenceScreen());
    }

    final SharedPreferences getSharedPreferences() {
        return getPreferenceManager().getSharedPreferences();
    }

    @Override
    public void onCreatePreferences(final Bundle savedInstanceState, final String s) {
        // this must be overridden, but is useless, because it's called during onCreate
        // so there is no possibility of calling setStorageDeviceProtected before this is called...
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            getPreferenceManager().setStorageDeviceProtected();
        }
        mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
                final SubScreenFragment fragment = SubScreenFragment.this;
                final Context context = fragment.getActivity();
                if (context == null || fragment.getPreferenceScreen() == null) {
                    final String tag = fragment.getClass().getSimpleName();
                    // TODO: Introduce a static function to register this class and ensure that
                    // onCreate must be called before "onSharedPreferenceChanged" is called.
                    Log.w(tag, "onSharedPreferenceChanged called before activity starts.");
                    return;
                }
                new BackupManager(context).dataChanged();
                fragment.onSharedPreferenceChanged(prefs, key);
            }
        };
        getSharedPreferences().registerOnSharedPreferenceChangeListener(
                mSharedPreferenceChangeListener);
    }

    @Override
    public void onResume() {
        super.onResume();
        final Activity activity = getActivity();
        if (activity instanceof AppCompatActivity) {
            final ActionBar actionBar = ((AppCompatActivity) activity).getSupportActionBar();
            final PreferenceScreen ps = getPreferenceScreen();
            if (ps == null) return;
            final CharSequence screenTitle = ps.getTitle();
            if (actionBar != null && screenTitle != null) {
                actionBar.setTitle(screenTitle);
            }
        }
    }

    @Override
    public void onDestroy() {
        getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
                mSharedPreferenceChangeListener);
        super.onDestroy();
    }

    @Override
    public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
        // This method may be overridden by an extended class.
    }

    // for fixing the indent appearing with androidx preferences
    // we don't have icons in subscreens, so we don't want indent
    // should also be possible in xml, but didn't find a way to have it in a theme/style
    @Override
    public void setPreferenceScreen(PreferenceScreen preferenceScreen) {
        super.setPreferenceScreen(preferenceScreen);
        if (preferenceScreen == null) return;
        int count = preferenceScreen.getPreferenceCount();
        for (int i = 0; i < count; i++) {
            final Preference pref = preferenceScreen.getPreference(i);
            pref.setIconSpaceReserved(false);
            if (pref instanceof PreferenceCategory) {
                final int subPrefCount = ((PreferenceCategory) pref).getPreferenceCount();
                for (int j = 0; j < subPrefCount; j++) {
                    ((PreferenceCategory) pref).getPreference(j).setIconSpaceReserved(false);
                }
            }
        }
    }
}
