<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_currency_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CurrencyListActivity">

    <!-- Кнопка "Назад" -->
    <Button
        android:id="@+id/button_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Назад"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <!-- Кнопка "Добавить пару" -->
    <Button
        android:id="@+id/button_add_pair"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Добавить пару"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <!-- Switch для ежедневных оповещений -->
    <Switch
        android:id="@+id/switch_daily_notifications"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Включить ежедневные оповещения"
        app:layout_constraintTop_toBottomOf="@id/button_add_pair"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <!-- Текстовое поле для пустого списка -->
    <TextView
        android:id="@+id/text_empty"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Нет избранных пар валют."
        android:textSize="18sp"
        android:textColor="#757575"
        android:gravity="center"
        android:visibility="gone"
        app:layout_constraintTop_toBottomOf="@id/switch_daily_notifications"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <!-- RecyclerView для отображения списка валют -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/currency_recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:padding="8dp"
        app:layout_constraintTop_toBottomOf="@id/switch_daily_notifications"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout> package com.example.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.app.NotificationManager;
import android.content.SharedPreferences;
import androidx.core.app.NotificationCompat;
import java.util.Set;

/**
 * BroadcastReceiver that handles daily notifications for favorite currency exchange rates.
 */
public class DailyNotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Access the SharedPreferences where favorite currency pairs are stored
        SharedPreferences prefs = context.getSharedPreferences("favorites", Context.MODE_PRIVATE);

        // Retrieve the set of favorite currency pairs
        Set<String> favoritePairs = prefs.getStringSet("favorite_pairs", null);

        // Proceed only if there are favorite pairs to report
        if (favoritePairs != null && !favoritePairs.isEmpty()) {
            StringBuilder contentBuilder = new StringBuilder();

            // Create an instance of CurrencyRepository to access exchange rates
            CurrencyRepository repository = new CurrencyRepository(context);

            // Loop through each favorite currency pair
            for (String pair : favoritePairs) {
                // Split the pair into base currency and target currency
                String[] currencies = pair.split("/");

                // Ensure that the pair is valid with exactly two currencies
                if (currencies.length == 2) {
                    String fromCurrency = currencies[0]; // Base currency
                    String toCurrency = currencies[1];   // Target currency

                    // Fetch the latest exchange rate from the repository
                    Double rate = repository.getExchangeRate(fromCurrency, toCurrency);

                    if (rate != null) {
                        // Append the formatted exchange rate to the notification content
                        contentBuilder.append(String.format("%s/%s: %.4f\n", fromCurrency, toCurrency, rate));
                    } else {
                        // Handle case where exchange rate data is not available
                        contentBuilder.append(String.format("%s/%s: нет данных\n", fromCurrency, toCurrency));
                    }
                } else {
                    // Handle invalid pair format
                    contentBuilder.append(String.format("%s: неверный формат пары\n", pair));
                }
            }

            String contentText = contentBuilder.toString();


            // Build and display the notification
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "daily_rate_channel")
                    .setContentTitle("Курсы избранных валют")
                    .setContentText(contentText)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(contentText)) // Supports longer text
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true);

            // Get the NotificationManager service to display the notification
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);


            // Display the notification with a unique ID
            if (notificationManager != null) {
                notificationManager.notify(1, builder.build());
            }
        } else {
            // Optionally handle the case when there are no favorite pairs
            // For example, you might log this information or skip notification
        }
    }
} package com.example.myapplication;

import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CurrencyListActivity extends AppCompatActivity {

    // RecyclerView to display the list of favorite currency pairs
    private RecyclerView recyclerView;

    // Adapter to manage the data and bind it to the RecyclerView
    private CurrencyAdapter currencyAdapter;

    // Repository to fetch currency data
    private CurrencyRepository repository;

    // Set to store favorite currency pairs
    private Set<String> favoriteCurrencyPairs;

    // TextView to display when no favorite pairs exist
    private TextView textEmpty;

    private Switch switchDailyNotifications;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_currency_list);

        // Initialize the repository
        repository = new CurrencyRepository(this);

        // Retrieve favorite currency pairs from SharedPreferences
        favoriteCurrencyPairs = getFavoriteCurrencyPairs();

        // Initialize RecyclerView and set its layout manager
        recyclerView = findViewById(R.id.currency_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // Reference to the empty state TextView
        textEmpty = findViewById(R.id.text_empty);

        // Initialize the adapter with the list of favorite pairs and set the click listener
        currencyAdapter = new CurrencyAdapter(new ArrayList<>(favoriteCurrencyPairs), new CurrencyAdapter.OnFavoriteClickListener() {
            @Override
            public void onFavoriteClick(String currencyPair, boolean isFavorite) {
                // Handle the favorite button click

                if (isFavorite) {
                    // If marking as favorite (adding)
                    favoriteCurrencyPairs.add(currencyPair);
                    Toast.makeText(CurrencyListActivity.this, "Добавлено в избранное: " + currencyPair, Toast.LENGTH_SHORT).show();
                } else {
                    // If unmarking as favorite (removing)
                    favoriteCurrencyPairs.remove(currencyPair);
                    Toast.makeText(CurrencyListActivity.this, "Удалено из избранного: " + currencyPair, Toast.LENGTH_SHORT).show();
                }

                // Save the updated favorite pairs to SharedPreferences
                saveFavoriteCurrencyPairs(favoriteCurrencyPairs);

                // Update the UI to reflect changes
                updateUI();
            }
        });

        // Set the adapter to the RecyclerView
        recyclerView.setAdapter(currencyAdapter);

        switchDailyNotifications = findViewById(R.id.switch_daily_notifications);

// Retrieve saved state
        SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
        boolean isNotificationsEnabled = prefs.getBoolean("daily_notifications_enabled", false);
        switchDailyNotifications.setChecked(isNotificationsEnabled);

// Set up listener
        switchDailyNotifications.setOnCheckedChangeListener((buttonView, isChecked) -> {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("daily_notifications_enabled", isChecked);
            editor.apply();

            if (isChecked) {
                scheduleDailyNotification();
            } else {
                cancelDailyNotification();
            }
        });


        // Initialize and set the "Back" button listener to finish the activity
        Button backButton = findViewById(R.id.button_back);
        backButton.setOnClickListener(v -> finish());

        // Initialize and set the "Add Pair" button listener to open the add pair dialog
        Button addPairButton = findViewById(R.id.button_add_pair);
        addPairButton.setOnClickListener(v -> new LoadCurrenciesTaskForDialog().execute());

        // Update the UI based on whether there are favorite pairs
        updateUI();
    }

    /**
     * Retrieves the set of favorite currency pairs from SharedPreferences.
     *
     * @return A new HashSet containing the favorite currency pairs.
     */
    private Set<String> getFavoriteCurrencyPairs() {
        SharedPreferences prefs = getSharedPreferences("favorites", MODE_PRIVATE);
        Set<String> defaultSet = new HashSet<>();
        Set<String> storedSet = prefs.getStringSet("favorite_pairs", defaultSet);
        // Return a new HashSet to avoid modifying the original set from SharedPreferences
        return new HashSet<>(storedSet);
    }

    /**
     * Saves the updated set of favorite currency pairs to SharedPreferences.
     *
     * @param favorites The set of favorite currency pairs to save.
     */
    private void saveFavoriteCurrencyPairs(Set<String> favorites) {
        SharedPreferences prefs = getSharedPreferences("favorites", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putStringSet("favorite_pairs", favorites);
        editor.apply();
    }

    /**
     * Updates the UI by toggling the visibility of the RecyclerView and the empty state TextView.
     */
    private void updateUI() {
        if (favoriteCurrencyPairs.isEmpty()) {
            // If there are no favorite pairs, show the empty state message and hide the RecyclerView
            recyclerView.setVisibility(View.GONE);
            textEmpty.setVisibility(View.VISIBLE);
        } else {
            // If there are favorite pairs, show the RecyclerView and hide the empty state message
            recyclerView.setVisibility(View.VISIBLE);
            textEmpty.setVisibility(View.GONE);
        }
    }

    /**
     * AsyncTask to load the list of currencies in the background for the add pair dialog.
     */
    private class LoadCurrenciesTaskForDialog extends AsyncTask<Void, Void, List<String>> {
        @Override
        protected List<String> doInBackground(Void... voids) {
            // Fetch all unique currencies from the repository
            return repository.getAllUniqueCurrencies();
        }

        @Override
        protected void onPostExecute(List<String> currencies) {
            if (currencies != null && !currencies.isEmpty()) {
                // If currencies are available, show the add pair dialog
                showAddPairDialog(currencies);
            } else {
                // If no currencies are available, inform the user
                Toast.makeText(CurrencyListActivity.this, "Нет доступных валют для добавления.", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * Displays an AlertDialog allowing the user to select and add a new currency pair.
     *
     * @param currencies A list of available currency codes.
     */
    private void showAddPairDialog(List<String> currencies) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Добавить валютную пару");

        // Inflate the custom dialog layout
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_add_pair, null);
        Spinner spinnerBase = dialogView.findViewById(R.id.spinner_base);
        Spinner spinnerTarget = dialogView.findViewById(R.id.spinner_target);

        // Set up the adapters for the spinners
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, currencies);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerBase.setAdapter(adapter);
        spinnerTarget.setAdapter(adapter);

        // Set the custom view to the dialog
        builder.setView(dialogView);

        // Define the positive button action (Add)
        builder.setPositiveButton("Добавить", (dialog, which) -> {
            String base = spinnerBase.getSelectedItem().toString();
            String target = spinnerTarget.getSelectedItem().toString();

            // Validate that base and target currencies are not the same
            if (base.equals(target)) {
                Toast.makeText(this, "Базовая и целевая валюты не могут быть одинаковыми.", Toast.LENGTH_SHORT).show();
                return;
            }

            String pair = base + "/" + target;

            // Check if the pair already exists in favorites
            if (favoriteCurrencyPairs.contains(pair)) {
                Toast.makeText(this, "Эта пара уже добавлена в избранное.", Toast.LENGTH_SHORT).show();
                return;
            }

            // Add the new pair to favorites
            favoriteCurrencyPairs.add(pair);
            saveFavoriteCurrencyPairs(favoriteCurrencyPairs);

            // Update the adapter with the new pair
            currencyAdapter.addCurrencyPair(pair);

            // Inform the user
            Toast.makeText(this, "Добавлено в избранное: " + pair, Toast.LENGTH_SHORT).show();

            // Update the UI to reflect changes
            updateUI();
        });

        // Define the negative button action (Cancel)
        builder.setNegativeButton("Отмена", (dialog, which) -> dialog.dismiss());

        // Show the dialog
        builder.show();
    }

    private void scheduleDailyNotification() {
        // Create notification channel for Android O and above
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Daily Rate Channel";
            String description = "Channel for daily exchange rate notifications";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("daily_rate_channel", name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

        // Schedule the alarm
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(this, DailyNotificationReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // Set the time to 00:01
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 1);
        calendar.set(Calendar.SECOND, 0);

        // If the time is before now, schedule for next day
        if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        // Set the repeating alarm
        if (alarmManager != null) {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY, pendingIntent);
        }
    }

    private void cancelDailyNotification() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, DailyNotificationReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        if (alarmManager != null) {
            alarmManager.cancel(pendingIntent);
        }
    }

} отматываю в системе дату назад и время на 12 pm и когда 12 01pm оповещение не приходит