package com.example.myapplication;

import android.Manifest;
import android.app.TimePickerDialog;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
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.TextView;
import android.widget.Toast;

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

public class CurrencyListActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private CurrencyAdapter currencyAdapter;
    private CurrencyRepository repository;
    private Set<String> favoriteCurrencyPairs;
    private TextView textEmpty;
    private TextView textSelectedTime;
    private Button buttonSetTime;
    private static final int REQUEST_NOTIFICATION_PERMISSION = 1001;

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

        repository = new CurrencyRepository(this);
        favoriteCurrencyPairs = getFavoriteCurrencyPairs();

        recyclerView = findViewById(R.id.currency_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        textEmpty = findViewById(R.id.text_empty);
        textSelectedTime = findViewById(R.id.text_selected_time);

        currencyAdapter = new CurrencyAdapter(new ArrayList<>(favoriteCurrencyPairs), new CurrencyAdapter.OnFavoriteClickListener() {
            @Override
            public void onFavoriteClick(String currencyPair, boolean isFavorite) {
                if (isFavorite) {
                    favoriteCurrencyPairs.add(currencyPair);
                    Toast.makeText(CurrencyListActivity.this, "Добавлено в избранное: " + currencyPair, Toast.LENGTH_SHORT).show();
                } else {
                    favoriteCurrencyPairs.remove(currencyPair);
                    Toast.makeText(CurrencyListActivity.this, "Удалено из избранного: " + currencyPair, Toast.LENGTH_SHORT).show();
                }
                saveFavoriteCurrencyPairs(favoriteCurrencyPairs);
                updateUI();
            }
        });

        recyclerView.setAdapter(currencyAdapter);

        buttonSetTime = findViewById(R.id.button_set_notification_time);
        initializeNotificationTime();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestNotificationPermissionIfNeeded();
        }

        buttonSetTime.setOnClickListener(v -> showTimePickerDialog());

        Button backButton = findViewById(R.id.button_back);
        backButton.setOnClickListener(v -> finish());

        Button addPairButton = findViewById(R.id.button_add_pair);
        addPairButton.setOnClickListener(v -> new LoadCurrenciesTaskForDialog().execute());

        updateUI();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_NOTIFICATION_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Разрешение на уведомления предоставлено", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Разрешение на уведомления отклонено. Уведомления не будут работать.", Toast.LENGTH_LONG).show();
                textSelectedTime.setText("Время уведомлений: не установлено");
                CurrencyAlarmHelper.cancelAllNotifications(this);
            }
        }
    }

    private Set<String> getFavoriteCurrencyPairs() {
        SharedPreferences prefs = getSharedPreferences("favorites", MODE_PRIVATE);
        Set<String> defaultSet = new HashSet<>();
        Set<String> storedSet = prefs.getStringSet("favorite_pairs", defaultSet);
        return new HashSet<>(storedSet);
    }

    private void saveFavoriteCurrencyPairs(Set<String> favorites) {
        SharedPreferences prefs = getSharedPreferences("favorites", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putStringSet("favorite_pairs", favorites);
        editor.apply();
    }

    private void updateUI() {
        if (favoriteCurrencyPairs.isEmpty()) {
            recyclerView.setVisibility(View.GONE);
            textEmpty.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            textEmpty.setVisibility(View.GONE);
        }
    }

    private void initializeNotificationTime() {
        SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
        int savedHour = prefs.getInt("notification_hour", -1);
        int savedMinute = prefs.getInt("notification_minute", -1);

        if (savedHour != -1 && savedMinute != -1) {
            String time = String.format("%02d:%02d", savedHour, savedMinute);
            textSelectedTime.setText("Время уведомлений: " + time);
        } else {
            textSelectedTime.setText("Время уведомлений: не установлено");
        }
    }

    private void requestNotificationPermissionIfNeeded() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_NOTIFICATION_PERMISSION);
        }
    }

    private void showTimePickerDialog() {
        SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
        int savedHour = prefs.getInt("notification_hour", 8);
        int savedMinute = prefs.getInt("notification_minute", 0);

        TimePickerDialog timePickerDialog = new TimePickerDialog(this, (view, hourOfDay, minute) -> {
            saveNotificationTime(hourOfDay, minute);
            String time = String.format("%02d:%02d", hourOfDay, minute);
            textSelectedTime.setText("Время уведомлений: " + time);
            CurrencyAlarmHelper.scheduleDailyNotification(this, hourOfDay, minute);
            Toast.makeText(this, "Уведомления будут отправляться в " + time, Toast.LENGTH_SHORT).show();
        }, savedHour, savedMinute, true);

        timePickerDialog.setTitle("Выберите время уведомлений");
        timePickerDialog.show();
    }

    private void saveNotificationTime(int hour, int minute) {
        SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("notification_hour", hour);
        editor.putInt("notification_minute", minute);
        editor.apply();
    }

    private void cancelAllNotifications() {
        CurrencyAlarmHelper.cancelAllNotifications(this);
    }

    private class LoadCurrenciesTaskForDialog extends AsyncTask<Void, Void, List<String>> {
        @Override
        protected List<String> doInBackground(Void... voids) {
            return repository.getAllUniqueCurrencies();
        }

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

    private void showAddPairDialog(List<String> currencies) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Добавить валютную пару");

        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);

        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);

        builder.setView(dialogView);

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

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

            String pair = base + "/" + target;

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

            favoriteCurrencyPairs.add(pair);
            saveFavoriteCurrencyPairs(favoriteCurrencyPairs);
            currencyAdapter.addCurrencyPair(pair);
            Toast.makeText(this, "Добавлено в избранное: " + pair, Toast.LENGTH_SHORT).show();
            updateUI();
        });

        builder.setNegativeButton("Отмена", (dialog, which) -> dialog.dismiss());
        builder.show();
    }
}package com.example.myapplication;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;

import androidx.core.app.NotificationCompat;

import java.util.Set;

public class DailyNotificationReceiver extends BroadcastReceiver {

    private static final String CHANNEL_ID = "daily_rate_channel";
    private static final String NOTIFICATION_TITLE = "Курсы избранных валют";
    private static final int NOTIFICATION_ID = 1;

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            SharedPreferences prefs = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
            Set<String> favoritePairs = prefs.getStringSet("favorite_pairs", null);
            int notificationHour = prefs.getInt("notification_hour", -1);
            int notificationMinute = prefs.getInt("notification_minute", -1);

            if (favoritePairs != null && !favoritePairs.isEmpty() && notificationHour != -1 && notificationMinute != -1) {
                StringBuilder contentBuilder = new StringBuilder();
                CurrencyRepository repository = new CurrencyRepository(context);

                for (String pair : favoritePairs) {
                    String[] currencies = pair.split("/");
                    if (currencies.length == 2) {
                        String fromCurrency = currencies[0];
                        String toCurrency = currencies[1];
                        Double rate = repository.getExchangeRate(fromCurrency, toCurrency);
                        if (rate != null) {
                            contentBuilder.append(String.format("%s/%s: %.4f\n", fromCurrency, toCurrency, rate));
                        } else {
                            contentBuilder.append(String.format("%s/%s: нет данных\n", fromCurrency, toCurrency));
                        }
                    } else {
                        contentBuilder.append(String.format("%s: неверный формат пары\n", pair));
                    }
                }

                String contentText = contentBuilder.toString();
                createNotificationChannel(context);

                NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
                        .setSmallIcon(R.drawable.star)
                        .setContentTitle(NOTIFICATION_TITLE)
                        .setContentText("Курсы валют на сегодня")
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(contentText))
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                        .setAutoCancel(true);

                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

                if (notificationManager != null) {
                    notificationManager.notify(NOTIFICATION_ID, builder.build());
                }

                CurrencyAlarmHelper.scheduleDailyNotification(context, notificationHour, notificationMinute);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            if (notificationManager == null) {
                return;
            }

            if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
                NotificationChannel channel = new NotificationChannel(
                        CHANNEL_ID,
                        "Daily Rate Channel",
                        NotificationManager.IMPORTANCE_DEFAULT
                );
                channel.setDescription("Channel for daily exchange rate notifications");
                notificationManager.createNotificationChannel(channel);
            }
        }
    }
}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.os.Build;
import android.util.Log;

import java.util.Calendar;

public class CurrencyAlarmHelper {

    private static final String TAG = "CurrencyAlarmHelper";
    private static final String CHANNEL_ID = "daily_rate_channel";
    private static final String CHANNEL_NAME = "Daily Rate Channel";
    private static final String CHANNEL_DESCRIPTION = "Channel for daily exchange rate notifications";

    public static void scheduleDailyNotification(Context context, int hour, int minute) {
        createNotificationChannel(context);
        cancelAllNotifications(context);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager == null) {
            Log.e(TAG, "AlarmManager is not available");
            return;
        }

        Intent intent = new Intent(context, DailyNotificationReceiver.class);

        int pendingIntentFlags = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context,
                0,
                intent,
                pendingIntentFlags
        );

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        if (calendar.getTimeInMillis() <= System.currentTimeMillis()) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(
                    AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(),
                    pendingIntent
            );
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(
                    AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(),
                    pendingIntent
            );
        } else {
            alarmManager.set(
                    AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(),
                    pendingIntent
            );
        }

        Log.d(TAG, "Уведомление установлено на " + calendar.getTime().toString());
    }

    public static void cancelAllNotifications(Context context) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager == null) {
            Log.e(TAG, "AlarmManager is not available");
            return;
        }

        Intent intent = new Intent(context, DailyNotificationReceiver.class);

        int pendingIntentFlags = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context,
                0,
                intent,
                pendingIntentFlags
        );

        alarmManager.cancel(pendingIntent);
        Log.d(TAG, "All notifications and alarms have been canceled");
    }

    private static void createNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            if (notificationManager == null) {
                Log.e(TAG, "NotificationManager не доступен");
                return;
            }

            if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
                NotificationChannel channel = new NotificationChannel(
                        CHANNEL_ID,
                        CHANNEL_NAME,
                        NotificationManager.IMPORTANCE_DEFAULT
                );
                channel.setDescription(CHANNEL_DESCRIPTION);
                notificationManager.createNotificationChannel(channel);
                Log.d(TAG, "Notification Channel создан");
            } else {
                Log.d(TAG, "Notification Channel уже существует");
            }
        }
    }
} при установке времени оповещения перезапускается программа а при повторном выборе крашится