package com.foxx.androidcast;

/*********************************************************************
 * CastSettingsFragment.java
 * Created at: Sun 17 May 2026 18:17:14 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class CastSettingsFragment
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (6 commits, 227 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	cd27b0c2a7b01463d09e249600dd4f9c71c4791dee07eba2944f67e89a19491b
**********************************************************************/
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.foxx.androidcast.receiver.ReceiverPrefs;

/** Settings drawer content — swipe from the left edge on main screens. */
public class CastSettingsFragment extends Fragment {
    private final CastSettings senderSettings = new CastSettings();
    private final CastSettings receiverSettings = new CastSettings();

    private EditText usernameInput;
    private EditText pinInput;
    private CheckBox trayIconCheck;
    private Spinner themeSpinner;
    private Spinner languageSpinner;
    private int versionTapCount;
    private long versionTapWindowStartMs;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_cast_settings, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        TextView headerGlobal = view.findViewById(R.id.header_global);
        TextView headerSender = view.findViewById(R.id.header_sender);
        TextView headerReceiver = view.findViewById(R.id.header_receiver);
        headerGlobal.setText(R.string.settings_section_global);
        headerSender.setText(R.string.settings_section_sender);
        headerReceiver.setText(R.string.settings_section_receiver);
        TextView headerAppInfo = view.findViewById(R.id.header_app_info);
        if (headerAppInfo != null) {
            headerAppInfo.setText(R.string.settings_section_app_info);
        }

        usernameInput = view.findViewById(R.id.edit_username);
        pinInput = view.findViewById(R.id.edit_settings_pin);
        trayIconCheck = view.findViewById(R.id.check_tray_icon);
        CheckBox crashLogsCheck = view.findViewById(R.id.check_send_crash_logs);
        themeSpinner = view.findViewById(R.id.spinner_theme);
        languageSpinner = view.findViewById(R.id.spinner_language);

        senderSettings.copyFrom(AppPreferences.loadSenderDefaults(requireContext()));
        receiverSettings.copyFrom(AppPreferences.loadReceiverDefaults(requireContext()));

        AppCompatActivity activity = (AppCompatActivity) requireActivity();
        CastSettingsBinder.bindGlobal(activity, usernameInput, pinInput, trayIconCheck);
        CastSettingsBinder.bindTheme(activity, themeSpinner);
        CastSettingsBinder.bindLanguage(activity, languageSpinner);
        CastSettingsBinder.bindSender(activity, senderSettings);
        CastSettingsBinder.bindReceiver(activity, receiverSettings);
        bindAppInfo(view);
        styleSpinners(view);

        trayIconCheck.setOnCheckedChangeListener((btn, checked) -> {
            AppPreferences.setShowTrayIcon(requireContext(), checked);
            CastTrayNotifier.onPreferenceChanged(requireContext());
        });
        if (crashLogsCheck != null) {
            crashLogsCheck.setChecked(AppPreferences.isSendAnonymousCrashLogs(requireContext()));
            crashLogsCheck.setOnCheckedChangeListener((btn, checked) ->
                    AppPreferences.setSendAnonymousCrashLogs(requireContext(), checked));
        }
        themeSpinner.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            private boolean first = true;

            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, View v, int position, long id) {
                CastThemeHelper.AppThemeMode mode = CastSettingsBinder.themeModeAt(position);
                if (first) {
                    first = false;
                    return;
                }
                if (mode != AppPreferences.getThemeMode(requireContext())) {
                    AppPreferences.setThemeMode(requireContext(), mode);
                    Toast.makeText(requireContext(), R.string.theme_apply_restart, Toast.LENGTH_LONG).show();
                    requireActivity().recreate();
                }
            }

            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {}
        });
        languageSpinner.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            private boolean first = true;

            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, View v, int position, long id) {
                CastLocaleHelper.AppLocaleMode mode = CastSettingsBinder.localeModeAt(position);
                if (first) {
                    first = false;
                    return;
                }
                if (mode != AppPreferences.getLocaleMode(requireContext())) {
                    AppPreferences.setLocaleMode(requireContext(), mode);
                    CastLocaleHelper.applyStoredLocale(requireContext());
                    Toast.makeText(requireContext(), R.string.language_apply_restart, Toast.LENGTH_LONG).show();
                    requireActivity().recreate();
                }
            }

            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {}
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        AppCompatActivity activity = (AppCompatActivity) requireActivity();
        CastSettingsBinder.refreshReceiverPipFromPermissions(activity);
        CastSettingsBinder.refreshCodecSpinners(activity, senderSettings, receiverSettings);
    }

    @Override
    public void onPause() {
        saveAll();
        super.onPause();
    }

    private void bindAppInfo(View view) {
        TextView version = view.findViewById(R.id.text_app_version_value);
        TextView protocol = view.findViewById(R.id.text_app_protocol_value);
        TextView commit = view.findViewById(R.id.text_app_commit_value);
        TextView built = view.findViewById(R.id.text_app_built_value);
        TextView author = view.findViewById(R.id.text_app_author_value);
        View.OnClickListener devTap = v -> onDeveloperSettingsTap();
        if (version != null) {
            version.setText(VersionInfo.APP_VERSION_STRING);
            version.setOnClickListener(devTap);
        }
        View versionRow = view.findViewById(R.id.row_app_version);
        if (versionRow != null) {
            versionRow.setOnClickListener(devTap);
        }
        TextView versionLabel = view.findViewById(R.id.label_app_version);
        if (versionLabel != null) {
            versionLabel.setOnClickListener(devTap);
        }
        View appInfoSection = view.findViewById(R.id.section_app_info);
        if (appInfoSection != null) {
            appInfoSection.setOnClickListener(devTap);
        }
        if (protocol != null) {
            protocol.setText(VersionInfo.PROTO_VERSION_STRING);
        }
        if (commit != null) {
            commit.setText(VersionInfo.GIT_COMMIT_SHORT);
        }
        if (built != null) {
            built.setText(VersionInfo.BUILD_TIME_DISPLAY);
        }
        if (author != null) {
            author.setText(VersionInfo.GIT_COMMIT_AUTHOR);
        }
        View licensesBtn = view.findViewById(R.id.btn_licenses);
        if (licensesBtn != null) {
            licensesBtn.setOnClickListener(v ->
                    startActivity(new Intent(requireContext(), LicensesActivity.class)));
        }
        View resetBtn = view.findViewById(R.id.btn_reset_defaults);
        if (resetBtn != null) {
            resetBtn.setOnClickListener(v -> showResetDefaultsConfirm());
        }
    }

    private void styleSpinners(View root) {
        if (root instanceof Spinner) {
            Spinner spinner = (Spinner) root;
            spinner.setBackgroundResource(R.drawable.bg_settings_spinner);
            spinner.setPopupBackgroundResource(R.drawable.bg_settings_spinner_popup);
        }
        if (root instanceof android.view.ViewGroup) {
            android.view.ViewGroup group = (android.view.ViewGroup) root;
            for (int i = 0; i < group.getChildCount(); i++) {
                styleSpinners(group.getChildAt(i));
            }
        }
    }

    private void onDeveloperSettingsTap() {
        long now = SystemClock.elapsedRealtime();
        if (now - versionTapWindowStartMs > 2500) {
            versionTapCount = 0;
        }
        versionTapWindowStartMs = now;
        versionTapCount++;
        if (versionTapCount >= 5) {
            versionTapCount = 0;
            startActivity(new Intent(requireContext(), DeveloperSettingsActivity.class));
        }
    }

    private void saveAll() {
        if (usernameInput == null) {
            return;
        }
        AppCompatActivity activity = (AppCompatActivity) requireActivity();
        CastSettingsBinder.saveGlobal(activity, usernameInput, pinInput, trayIconCheck);
        CastSettingsBinder.saveTheme(activity, themeSpinner);
        CastSettingsBinder.saveLanguage(activity, languageSpinner);
        CastSettingsBinder.saveSender(activity, senderSettings);
        CastSettingsBinder.saveReceiver(activity, receiverSettings);
        ReceiverPrefs.setAllowAudio(requireContext(), AppPreferences.isPlayIncomingAudio(requireContext()));
        CastTrayNotifier.onPreferenceChanged(requireContext());
    }

    private void showResetDefaultsConfirm() {
        new AlertDialog.Builder(requireContext())
                .setMessage(R.string.reset_defaults_confirm)
                .setPositiveButton(android.R.string.yes, (d, which) -> {
                    AppPreferences.resetUserVisibleSettings(requireContext());
                    ReceiverPrefs.setAllowAudio(requireContext(), AppPreferences.isPlayIncomingAudio(requireContext()));
                    CastTrayNotifier.onPreferenceChanged(requireContext());
                    Toast.makeText(requireContext(), R.string.reset_defaults_done, Toast.LENGTH_SHORT).show();
                    requireActivity().recreate();
                })
                .setNegativeButton(android.R.string.no, null)
                .show();
    }
}
