package com.example.myapplication;

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;

@Database(entities = {CurrencyRate.class}, version = 3, exportSchema = false)
@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
    private static volatile AppDatabase INSTANCE;

    public abstract CurrencyRateDao currencyRateDao();

    public static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                                    AppDatabase.class, "currency_database")
                            .fallbackToDestructiveMigration()
                            .build();
                }
            }
        }
        return INSTANCE;
    }
}package com.example.myapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.button.MaterialButtonToggleGroup;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class ChartActivity extends AppCompatActivity {
    private static final String TAG = "ChartActivity";
    private CurrencyRepository repository;
    private LineChart lineChart;

    // Выбранные валюты
    private String fromCurrency;
    private String toCurrency;

    private MaterialButtonToggleGroup timeRangeToggleGroup;
    private MaterialButton buttonBackToMain;

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

        repository = new CurrencyRepository(this);
        lineChart = findViewById(R.id.line_chart);
        timeRangeToggleGroup = findViewById(R.id.time_range_toggle_group_chart);
        buttonBackToMain = findViewById(R.id.button_back_to_main);

        // Получение выбранных валют из Intent
        fromCurrency = getIntent().getStringExtra("FROM_CURRENCY");
        toCurrency = getIntent().getStringExtra("TO_CURRENCY");

        if (fromCurrency == null || toCurrency == null) {
            Toast.makeText(this, "Не выбраны валюты для отображения графика.", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // Настройка обработчика кнопок выбора периода
        timeRangeToggleGroup.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() {
            @Override
            public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) {
                if (isChecked) {
                    Log.d(TAG, "Выбран период: " + checkedId);
                    loadChartData(); // Перезагрузка графика при изменении периода
                }
            }
        });

        // Настройка обработчика кнопки "Назад"
        buttonBackToMain.setOnClickListener(v -> finish());

        // Инициализация графика и загрузка данных
        loadChartData();
    }

    /**
     * Загружает данные для графика на основе выбранных валют и периода.
     */
    private void loadChartData() {
        // Определение выбранного периода
        int checkedButtonId = timeRangeToggleGroup.getCheckedButtonId();
        int timeRangeDays;

        switch (checkedButtonId) {
            case R.id.button_30_days_chart:
                timeRangeDays = 30;
                break;
            case R.id.button_90_days_chart:
                timeRangeDays = 90;
                break;
            case R.id.button_7_days_chart:
            default:
                timeRangeDays = 7;
                break;
        }

        // Загрузка данных в фоновом потоке
        new LoadChartDataTask(fromCurrency, toCurrency, timeRangeDays).execute();
    }

    /**
     * AsyncTask для загрузки данных графика.
     */
    private class LoadChartDataTask extends AsyncTask<Void, Void, LineData> {
        private final String fromCurrency;
        private final String toCurrency;
        private final int timeRangeDays;
        private List<Date> dates;

        public LoadChartDataTask(String fromCurrency, String toCurrency, int timeRangeDays) {
            this.fromCurrency = fromCurrency;
            this.toCurrency = toCurrency;
            this.timeRangeDays = timeRangeDays;
        }

        @Override
        protected LineData doInBackground(Void... voids) {
            Date endDate = new Date();  // Текущая дата
            Calendar cal = Calendar.getInstance();
            cal.setTime(endDate);
            cal.add(Calendar.DAY_OF_YEAR, -timeRangeDays);
            Date startDate = cal.getTime();

            // Получение исторических данных для графика
            List<CurrencyRate> history = repository.getCurrencyRateHistoryWithinDates("USD", toCurrency, startDate, endDate);

            if (history == null || history.isEmpty()) {
                // Если необходим USD/USD, добавляем курс 1.0
                if (toCurrency.equals("USD")) {
                    history = generateUsdHistory(startDate, endDate);
                } else {
                    return null;
                }
            }

            if (history == null || history.isEmpty()) {
                return null;
            }

            List<Entry> entries = new ArrayList<>();
            dates = new ArrayList<>();

            int index = 0;
            for (CurrencyRate rate : history) {
                entries.add(new Entry(index, (float) rate.rate));
                dates.add(rate.date);
                index++;
            }

            LineDataSet dataSet = new LineDataSet(entries, "Курс " + fromCurrency + "/" + toCurrency);
            dataSet.setColor(ColorTemplate.getHoloBlue());
            dataSet.setLineWidth(2f);
            dataSet.setDrawCircles(false);
            dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            dataSet.setDrawFilled(true);
            dataSet.setFillAlpha(50);
            dataSet.setFillColor(ColorTemplate.getHoloBlue());
            dataSet.setDrawValues(false);

            return new LineData(dataSet);
        }

        /**
         * Генерирует список курсов USD/USD (стабильный курс 1.0).
         */
        private List<CurrencyRate> generateUsdHistory(Date startDate, Date endDate) {
            List<Date> allDates = repository.getAllDatesWithinRange(startDate, endDate);
            List<CurrencyRate> usdHistory = new ArrayList<>();
            for (Date date : allDates) {
                usdHistory.add(new CurrencyRate("USD", "USD", 1.0, date));
            }
            return usdHistory;
        }

        @Override
        protected void onPostExecute(LineData lineData) {
            if (lineData != null && lineData.getEntryCount() > 0) {
                XAxis xAxis = lineChart.getXAxis();
                xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
                xAxis.setLabelRotationAngle(-45f);
                xAxis.setGranularity(1f);
                xAxis.setDrawGridLines(false);
                xAxis.setValueFormatter(new ValueFormatter() {
                    private final SimpleDateFormat mFormat = new SimpleDateFormat("dd MMM", Locale.getDefault());

                    @Override
                    public String getFormattedValue(float value) {
                        int index = (int) value;
                        if (index >= 0 && index < dates.size()) {
                            Date date = dates.get(index);
                            return mFormat.format(date);
                        } else {
                            return "";
                        }
                    }
                });

                // Настраиваем ось Y
                lineChart.getAxisRight().setEnabled(false);

                // Обновляем данные графика
                lineChart.setData(lineData);

                // Разрешаем взаимодействие
                lineChart.setTouchEnabled(true);
                lineChart.setDragEnabled(true);
                lineChart.setScaleEnabled(true);

                // Устанавливаем кастомный MarkerView (при наличии)
                // Например:
                // CustomMarkerView markerView = new CustomMarkerView(ChartActivity.this, R.layout.custom_marker_view, dates);
                // markerView.setChartView(lineChart);
                // lineChart.setMarker(markerView);

                lineChart.invalidate();
            } else {
                lineChart.clear();
                lineChart.invalidate();
                Toast.makeText(ChartActivity.this, "Нет данных для отображения графика.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}package com.example.myapplication;

import android.os.AsyncTask;
import android.util.Log;







public class ConvertCurrencyTask extends AsyncTask<Void, Void, Double> {
    private final String fromCurrency;
    private final String toCurrency;
    private final double amount;
    private final CurrencyRepository repository;
    private final Callback callback;

    public interface Callback {
        void onConversionResult(Double result);
    }

    public ConvertCurrencyTask(String fromCurrency, String toCurrency, double amount, CurrencyRepository repository, Callback callback) {
        this.fromCurrency = fromCurrency;
        this.toCurrency = toCurrency;
        this.amount = amount;
        this.repository = repository;
        this.callback = callback;
    }

    @Override
    protected Double doInBackground(Void... voids) {
        // Get exchange rates relative to USD
        Double rateFromUSD;
        if (fromCurrency.equals("USD")) {
            rateFromUSD = 1.0;
        } else {
            rateFromUSD = repository.getExchangeRate("USD", fromCurrency);
            if (rateFromUSD != null) {
                rateFromUSD = 1 / rateFromUSD; // Convert to rate fromCurrency -> USD
            }
        }

        Double rateToUSD;
        if (toCurrency.equals("USD")) {
            rateToUSD = 1.0;
        } else {
            rateToUSD = repository.getExchangeRate("USD", toCurrency);
            if (rateToUSD != null) {
                rateToUSD = 1 / rateToUSD; // Convert to rate toCurrency -> USD
            }
        }

        if (rateFromUSD == null || rateToUSD == null) {
            Log.e("ConvertCurrencyTask", "Conversion rate not found for " + fromCurrency + " or " + toCurrency);
            return null;
        }

        // Correct cross-rate calculation
        double crossRate = rateFromUSD / rateToUSD;

        // Perform conversion
        return amount * crossRate;
    }



    @Override
    protected void onPostExecute(Double result) {
        callback.onConversionResult(result);
    }


}package com.example.myapplication;

import androidx.room.TypeConverter;

import java.util.Date;

public class Converters {
    @TypeConverter
    public static Date fromTimestamp(Long value) {
        return value == null ? null : new Date(value);
    }

    @TypeConverter
    public static Long dateToTimestamp(Date date) {
        return date == null ? null : date.getTime();
    }
}package com.example.myapplication;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.CheckBox;

import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.R;

import java.util.List;
import java.util.Set;

public class CurrencyAdapter extends RecyclerView.Adapter<CurrencyAdapter.ViewHolder> {

    private List<String> currencies;
    private Set<String> favoriteCurrencies;
    private OnFavoriteClickListener listener;

    public interface OnFavoriteClickListener {
        void onFavoriteClick(String currency, boolean isFavorite);
    }

    public CurrencyAdapter(List<String> currencies, Set<String> favoriteCurrencies, OnFavoriteClickListener listener) {
        this.currencies = currencies;
        this.favoriteCurrencies = favoriteCurrencies;
        this.listener = listener;
    }

    @Override
    public CurrencyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.currency_item, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(CurrencyAdapter.ViewHolder holder, int position) {
        String currency = currencies.get(position);
        holder.currencyName.setText(currency);

        // Убираем слушатель перед сменой состояния
        holder.favoriteCheckBox.setOnCheckedChangeListener(null);
        holder.favoriteCheckBox.setChecked(favoriteCurrencies.contains(currency));

        // Устанавливаем слушатель
        holder.favoriteCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (listener != null) {
                listener.onFavoriteClick(currency, isChecked);
            }
        });
    }

    @Override
    public int getItemCount() {
        return currencies.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView currencyName;
        public CheckBox favoriteCheckBox;

        public ViewHolder(View itemView) {
            super(itemView);
            currencyName = itemView.findViewById(R.id.currency_name);
            favoriteCheckBox = itemView.findViewById(R.id.favorite_checkbox);
        }
    }
}package com.example.myapplication;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.View;
import android.widget.Button;

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

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

        repository = new CurrencyRepository(this);
        favoriteCurrencies = getFavoriteCurrencies();

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

        // Настраиваем кнопку "Назад"
        Button backButton = findViewById(R.id.button_back);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });

        new LoadCurrenciesTask().execute();
    }


    private void loadCurrencies(List<String> currencies) {
        currencyAdapter = new CurrencyAdapter(currencies, favoriteCurrencies, new CurrencyAdapter.OnFavoriteClickListener() {
            @Override
            public void onFavoriteClick(String currency, boolean isFavorite) {
                if (isFavorite) {
                    favoriteCurrencies.add(currency);
                } else {
                    favoriteCurrencies.remove(currency);
                }
                saveFavoriteCurrencies(favoriteCurrencies);
            }
        });
        recyclerView.setAdapter(currencyAdapter);
    }

    private Set<String> getFavoriteCurrencies() {
        SharedPreferences prefs = getSharedPreferences("favorites", MODE_PRIVATE);
        return new HashSet<>(prefs.getStringSet("favorite_currencies", new HashSet<>()));
    }

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

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

        @Override
        protected void onPostExecute(List<String> currencies) {
            Log.d("LoadCurrenciesTask", "onPostExecute with currencies: " + currencies.toString());
            loadCurrencies(currencies);
        }
    }
}package com.example.myapplication;

import androidx.room.Entity;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverters;

import java.util.Date;

@Entity(tableName = "currency_rate")
public class CurrencyRate {
    @PrimaryKey(autoGenerate = true)
    public int id;

    public String baseCurrency;
    public String targetCurrency;
    public double rate;

    @TypeConverters({Converters.class})
    public Date date;

    public CurrencyRate(String baseCurrency, String targetCurrency, double rate, Date date) {
        this.baseCurrency = baseCurrency;
        this.targetCurrency = targetCurrency;
        this.rate = rate;
        this.date = date;
    }

    @Override
    public String toString() {
        return baseCurrency + " -> " + targetCurrency + " = " + rate + " на " + date.toString();
    }
}package com.example.myapplication;

import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;

import java.util.Date;
import java.util.List;

@Dao
public interface CurrencyRateDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertCurrencyRate(CurrencyRate rate);

    /**
     * Пакетная вставка курсов валют.
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertCurrencyRates(List<CurrencyRate> rates);

    @Query("DELETE FROM currency_rate")
    void clearAllRates();

    @Query("SELECT DISTINCT baseCurrency FROM currency_rate")
    List<String> getAllBaseCurrencies();

    @Query("SELECT DISTINCT targetCurrency FROM currency_rate")
    List<String> getAllTargetCurrencies();

    @Query("SELECT DISTINCT date FROM currency_rate WHERE date BETWEEN :startDate AND :endDate ORDER BY date DESC")
    List<Date> getAllDatesWithinRange(Date startDate, Date endDate);

    @Query("SELECT * FROM currency_rate WHERE baseCurrency = :baseCurrency AND targetCurrency = :targetCurrency AND date BETWEEN :startDate AND :endDate ORDER BY date DESC")
    List<CurrencyRate> getCurrencyRateHistoryWithinDates(String baseCurrency, String targetCurrency, Date startDate, Date endDate);

    @Query("SELECT rate FROM currency_rate WHERE baseCurrency = :fromCurrency AND targetCurrency = :toCurrency ORDER BY date DESC LIMIT 1")
    Double getLatestExchangeRate(String fromCurrency, String toCurrency);

    @Query("SELECT DISTINCT date FROM currency_rate ORDER BY date DESC")
    List<Date> getAllDates();
}package com.example.myapplication;

import android.content.Context;
import android.util.Log;

import com.example.myapplication.api.LoadCurrencyRatesTask;

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

public class CurrencyRepository {
    private final CurrencyRateDao currencyRateDao;
    private final Context context;

    public CurrencyRepository(Context context) {
        this.context = context;
        AppDatabase db = AppDatabase.getDatabase(context);
        currencyRateDao = db.currencyRateDao();
    }

    public void insertCurrencyRateSync(CurrencyRate rate) {
        currencyRateDao.insertCurrencyRate(rate);
        Log.d("CurrencyRepository", "Вставлен курс: " + rate.toString());
    }

    /**
     * Пакетная вставка курсов валют.
     */
    public void insertCurrencyRatesSync(List<CurrencyRate> rates) {
        currencyRateDao.insertCurrencyRates(rates);
        Log.d("CurrencyRepository", "Вставлены курсы валют: " + rates.size());
    }

    public void clearAllRates() {
        currencyRateDao.clearAllRates();
        Log.d("CurrencyRepository", "Все курсы очищены из базы данных.");
    }

    public List<Date> getAllDates() {
        return currencyRateDao.getAllDates();
    }

    // Метод для получения дат в заданном диапазоне
    public List<Date> getAllDatesWithinRange(Date startDate, Date endDate) {
        List<Date> dates = currencyRateDao.getAllDatesWithinRange(startDate, endDate);
        Log.d("CurrencyRepository", "Получены даты в диапазоне: " + dates.toString());
        return dates;
    }

    // Метод для получения исторических данных курса за заданный период
    public List<CurrencyRate> getCurrencyRateHistoryWithinDates(String baseCurrency, String targetCurrency, Date startDate, Date endDate) {
        List<CurrencyRate> rates = currencyRateDao.getCurrencyRateHistoryWithinDates(baseCurrency, targetCurrency, startDate, endDate);
        Log.d("CurrencyRepository", "Получены курсы для " + baseCurrency + "/" + targetCurrency + " в диапазоне: " + rates.toString());
        return rates;
    }

    public List<String> getAllUniqueCurrencies() {
        List<String> baseCurrencies = currencyRateDao.getAllBaseCurrencies();
        List<String> targetCurrencies = currencyRateDao.getAllTargetCurrencies();
        Set<String> allCurrencies = new HashSet<>(baseCurrencies);
        allCurrencies.addAll(targetCurrencies);
        List<String> uniqueCurrencies = new ArrayList<>(allCurrencies);
        Log.d("CurrencyRepository", "Уникальные валюты: " + uniqueCurrencies.toString());
        return uniqueCurrencies;
    }

    public Double getExchangeRate(String fromCurrency, String toCurrency) {
        Double rate = currencyRateDao.getLatestExchangeRate(fromCurrency, toCurrency);
        Log.d("CurrencyRepository", "Последний курс с " + fromCurrency + " на " + toCurrency + ": " + rate);
        return rate;
    }

    public void loadAllCurrencyRatesFromApi(LoadCurrencyRatesTask.Callback callback) {
        new LoadCurrencyRatesTask(context, this, callback).execute();
    }
}package com.example.myapplication;

import android.content.Context;
import android.widget.TextView;

import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.example.myapplication.R;
import com.github.mikephil.charting.utils.MPPointF;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class CustomMarkerView extends MarkerView {

    private final TextView tvContent;
    private final List<Date> dates;
    private MPPointF mOffset;

    public CustomMarkerView(Context context, int layoutResource, List<Date> dates) {
        super(context, layoutResource);
        this.dates = dates;
        tvContent = findViewById(R.id.tvContent);
    }

    @Override
    public void refreshContent(Entry e, Highlight highlight) {
        int index = (int) e.getX();
        if (index >= 0 && index < dates.size()) {
            Date date = dates.get(index);
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault());
            String dateStr = dateFormat.format(date);
            String rateStr = String.format(Locale.getDefault(), "%.4f", e.getY());
            tvContent.setText(dateStr + "\nКурс: " + rateStr);
        } else {
            tvContent.setText("");
        }
        super.refreshContent(e, highlight);
    }

    @Override
    public MPPointF getOffset() {
        if (mOffset == null) {
            mOffset = new MPPointF(-(getWidth() / 2f), -getHeight());
        }
        return mOffset;
    }
}package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log; // Добавлено для логирования
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.api.LoadCurrencyRatesTask;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry; // Импорт Entry для точек данных на графике
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet; // Импорт LineDataSet для набора данных
import com.github.mikephil.charting.formatter.ValueFormatter; // Импорт ValueFormatter для пользовательских подписей оси
import com.github.mikephil.charting.utils.ColorTemplate; // Импорт ColorTemplate для цветов
import com.google.android.material.button.MaterialButton;
import com.google.android.material.button.MaterialButtonToggleGroup;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private Spinner spinnerFrom;
    private Spinner spinnerTo;
    private EditText inputFrom;
    private EditText inputTo;
    private ProgressBar loadingIndicator;
    private CurrencyRepository repository;
    private MaterialButtonToggleGroup timeRangeToggleGroup;
    private MaterialButton buttonSwap;
    private MaterialButton buttonShowChart; // Новая кнопка для перехода к графику

    private boolean isRatesLoaded = false;

    private LineChart lineChart; // Инициализация графика

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Инициализация компонентов
        repository = new CurrencyRepository(this);
        spinnerFrom = findViewById(R.id.spinner_from);
        spinnerTo = findViewById(R.id.spinner_to);
        inputFrom = findViewById(R.id.input_from);
        inputTo = findViewById(R.id.input_to);
        loadingIndicator = findViewById(R.id.loading_indicator);
        lineChart = findViewById(R.id.line_chart); // Инициализация графика
        timeRangeToggleGroup = findViewById(R.id.time_range_toggle_group);
        buttonSwap = findViewById(R.id.button_swap);
        buttonShowChart = findViewById(R.id.button_show_chart); // Инициализация новой кнопки

        // Настройка обработчика кнопки перехода к графику
        buttonShowChart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isRatesLoaded) {
                    Intent intent = new Intent(MainActivity.this, ChartActivity.class);
                    String selectedFromCurrency = spinnerFrom.getSelectedItem().toString();
                    String selectedToCurrency = spinnerTo.getSelectedItem().toString();
                    intent.putExtra("FROM_CURRENCY", selectedFromCurrency);
                    intent.putExtra("TO_CURRENCY", selectedToCurrency);
                    startActivity(intent);
                } else {
                    showToast("Подождите, пока загрузятся курсы валют.");
                }
            }
        });

        // Настройка обработчика кнопки свапа
        buttonSwap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int fromPosition = spinnerFrom.getSelectedItemPosition();
                int toPosition = spinnerTo.getSelectedItemPosition();

                spinnerFrom.setSelection(toPosition);
                spinnerTo.setSelection(fromPosition);

                // Обмен значениями в полях ввода (опционально)
                String inputFromValue = inputFrom.getText().toString();
                String inputToValue = inputTo.getText().toString();
                inputFrom.setText(inputToValue);
                inputTo.setText(inputFromValue);

                if (isRatesLoaded) {
                    performConversion();
                    loadChartData();
                } else {
                    showToast("Подождите, пока загрузятся курсы валют.");
                }
            }
        });

        // Показываем индикатор загрузки и загружаем курсы
        loadingIndicator.setVisibility(View.VISIBLE);
        repository.loadAllCurrencyRatesFromApi(new LoadCurrencyRatesTask.Callback() {
            @Override
            public void onRatesLoaded() {
                runOnUiThread(() -> {
                    new LoadCurrenciesTask().execute();
                });
            }

            @Override
            public void onError(Exception e) {
                runOnUiThread(() -> {
                    // Не очищаем базу данных, используем кэшированные данные
                    loadingIndicator.setVisibility(View.GONE);
                    showToast("Ошибка обновления курсов валют: " + e.getMessage());
                    Log.e("MainActivity", "Error updating currency rates", e);
                    // Теперь загружаем данные из кэша
                    new LoadCurrenciesTask().execute();
                });
            }
        });

        // Настройка слушателя для выбора периода
        timeRangeToggleGroup.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() {
            @Override
            public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) {
                if (isChecked) {
                    Log.d("MainActivity", "Кнопка проверена: " + checkedId);
                    if (isRatesLoaded) {
                        performConversion();
                        loadChartData(); // Загружаем данные для графика при изменении выбора периода
                    } else {
                        showToast("Подождите, пока загрузятся курсы валют.");
                    }
                } else {
                    Log.d("MainActivity", "Кнопка снята: " + checkedId);
                }
            }
        });

        // Настройка слушателя для изменения текста в поле ввода суммы
        inputFrom.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // Без действий
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // Без действий
            }
            @Override
            public void afterTextChanged(Editable s) {
                if (isRatesLoaded) {
                    performConversion();
                } else {
                    showToast("Подождите, пока загрузятся курсы валют.");
                }
            }
        });

        // Настройка слушателя для выбора валют из спиннеров
        AdapterView.OnItemSelectedListener spinnerListener = new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isRatesLoaded) {
                    performConversion();
                    loadChartData(); // Загружаем данные для графика при изменении выбора
                }
            }

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

        spinnerFrom.setOnItemSelectedListener(spinnerListener);
        spinnerTo.setOnItemSelectedListener(spinnerListener);
    }

    /**
     * Загружает данные для графика.
     */
    private void loadChartData() {
        String fromCurrency = spinnerFrom.getSelectedItem().toString().toUpperCase();
        String toCurrency = spinnerTo.getSelectedItem().toString().toUpperCase();

        int timeRangeDays = 7;  // Значение по умолчанию
        int checkedButtonId = timeRangeToggleGroup.getCheckedButtonId();

        if (checkedButtonId == R.id.button_7_days) {
            timeRangeDays = 7;
        } else if (checkedButtonId == R.id.button_30_days) {
            timeRangeDays = 30;
        } else if (checkedButtonId == R.id.button_90_days) {
            timeRangeDays = 90;
        } else {
            timeRangeDays = 7; // По умолчанию 7 дней, если ничего не выбрано
        }

        new LoadChartDataTask(fromCurrency, toCurrency, timeRangeDays).execute();
    }

    /**
     * AsyncTask для загрузки данных графика.
     */
    private class LoadChartDataTask extends AsyncTask<Void, Void, LineData> {
        private final String fromCurrency;
        private final String toCurrency;
        private final int timeRangeDays;
        private List<Date> dates;

        public LoadChartDataTask(String fromCurrency, String toCurrency, int timeRangeDays) {
            this.fromCurrency = fromCurrency;
            this.toCurrency = toCurrency;
            this.timeRangeDays = timeRangeDays;
        }

        @Override
        protected LineData doInBackground(Void... voids) {
            Date endDate = new Date();  // Текущая дата
            Calendar cal = Calendar.getInstance();
            cal.setTime(endDate);
            cal.add(Calendar.DAY_OF_YEAR, -timeRangeDays);
            Date startDate = cal.getTime();

            List<CurrencyRate> historyFrom = repository.getCurrencyRateHistoryWithinDates("USD", fromCurrency, startDate, endDate);
            List<CurrencyRate> historyTo = repository.getCurrencyRateHistoryWithinDates("USD", toCurrency, startDate, endDate);

            if (fromCurrency.equals("USD")) {
                historyFrom = generateUsdHistory(startDate, endDate);
            }

            if (toCurrency.equals("USD")) {
                historyTo = generateUsdHistory(startDate, endDate);
            }

            if (historyFrom == null || historyTo == null ||
                    historyFrom.isEmpty() || historyTo.isEmpty()) {
                return null;
            }

            int size = Math.min(historyFrom.size(), historyTo.size());
            List<Entry> entries = new ArrayList<>();
            dates = new ArrayList<>();

            for (int i = 0; i < size; i++) {
                CurrencyRate rateFrom = historyFrom.get(i);
                CurrencyRate rateTo = historyTo.get(i);

                double rateFromUSD = rateFrom.rate;
                double rateToUSD = rateTo.rate;

                double crossRate = rateToUSD / rateFromUSD;

                entries.add(new Entry(i, (float) crossRate));
                dates.add(rateFrom.date);
            }

            LineDataSet dataSet = new LineDataSet(entries, "Курс " + fromCurrency + "/" + toCurrency);
            dataSet.setColor(ColorTemplate.getHoloBlue());
            dataSet.setLineWidth(2f);
            dataSet.setDrawCircles(false);
            dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            dataSet.setDrawFilled(true);
            dataSet.setFillAlpha(50);
            dataSet.setFillColor(ColorTemplate.getHoloBlue());
            dataSet.setDrawValues(false);

            return new LineData(dataSet);
        }

        /**
         * Генерирует список курсов USD/USD (стабильный курс 1.0).
         */
        private List<CurrencyRate> generateUsdHistory(Date startDate, Date endDate) {
            List<Date> allDates = repository.getAllDatesWithinRange(startDate, endDate);
            List<CurrencyRate> usdHistory = new ArrayList<>();
            for (Date date : allDates) {
                usdHistory.add(new CurrencyRate("USD", "USD", 1.0, date));
            }
            return usdHistory;
        }

        @Override
        protected void onPostExecute(LineData lineData) {
            if (lineData != null && lineData.getEntryCount() > 0) {
                XAxis xAxis = lineChart.getXAxis();
                xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
                xAxis.setLabelRotationAngle(-45f);
                xAxis.setGranularity(1f);
                xAxis.setDrawGridLines(false);
                xAxis.setValueFormatter(new ValueFormatter() {
                    private final SimpleDateFormat mFormat = new SimpleDateFormat("dd MMM", Locale.getDefault());

                    @Override
                    public String getFormattedValue(float value) {
                        int index = (int) value;
                        if (index >= 0 && index < dates.size()) {
                            Date date = dates.get(index);
                            return mFormat.format(date);
                        } else {
                            return "";
                        }
                    }
                });

                // Настраиваем ось Y
                lineChart.getAxisRight().setEnabled(false);

                // Обновляем данные графика
                lineChart.setData(lineData);

                // Разрешаем взаимодействие
                lineChart.setTouchEnabled(true);
                lineChart.setDragEnabled(true);
                lineChart.setScaleEnabled(true);

                // Устанавливаем кастомный MarkerView (при наличии)
                // Например:
                // CustomMarkerView markerView = new CustomMarkerView(MainActivity.this, R.layout.custom_marker_view, dates);
                // markerView.setChartView(lineChart);
                // lineChart.setMarker(markerView);

                lineChart.invalidate();
            } else {
                lineChart.clear();
                lineChart.invalidate();
                showToast("Нет данных для отображения графика.");
            }
        }
    }

    /**
     * AsyncTask для загрузки списка валют после обновления курсов.
     */
    private class LoadCurrenciesTask extends AsyncTask<Void, Void, List<String>> {
        @Override
        protected void onPreExecute() {
            loadingIndicator.setVisibility(View.VISIBLE);
        }

        @Override
        protected List<String> doInBackground(Void... voids) {
            // Загрузка списка валют из репозитория
            List<String> currencies = repository.getAllUniqueCurrencies();
            Log.d("LoadCurrenciesTask", "Получены валюты: " + currencies.toString());
            return currencies;
        }

        @Override
        protected void onPostExecute(List<String> currencies) {
            super.onPostExecute(currencies);
            loadingIndicator.setVisibility(View.GONE);
            Log.d("LoadCurrenciesTask", "onPostExecute с валютами: " + currencies);
            if (currencies != null && !currencies.isEmpty()) {
                isRatesLoaded = true;
                ArrayAdapter<String> adapterFrom = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, currencies);
                adapterFrom.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerFrom.setAdapter(adapterFrom);

                ArrayAdapter<String> adapterTo = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, currencies);
                adapterTo.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerTo.setAdapter(adapterTo);

                // Устанавливаем стандартные значения
                spinnerFrom.setSelection(0);
                spinnerTo.setSelection(1);

                // Выполняем конвертацию и загружаем данные для графика
                performConversion();
                loadChartData();

                // Устанавливаем кнопку по умолчанию в ToggleGroup
                timeRangeToggleGroup.check(R.id.button_7_days);
            } else {
                if (!isInternetAvailable()) { // Метод для проверки сети
                    showToast("Нет интернет-соединения и нет кэшированных данных.");
                } else {
                    showToast("Не удалось загрузить валюты.");
                }
                Log.e("LoadCurrenciesTask", "Список валют пуст");
            }
        }
    }

    /**
     * Выполняет конвертацию валюты.
     */
    private void performConversion() {
        String fromCurrency = spinnerFrom.getSelectedItem().toString().toUpperCase();
        String toCurrency = spinnerTo.getSelectedItem().toString().toUpperCase();
        String amountStr = inputFrom.getText().toString();

        if (amountStr.isEmpty()) {
            inputTo.setText("");
            return;
        }

        if (fromCurrency.equals(toCurrency)) {
            inputTo.setText(amountStr);
            return;
        }

        try {
            double amount = Double.parseDouble(amountStr);

            // Выполняем конвертацию
            new ConvertCurrencyTask(fromCurrency, toCurrency, amount, repository, result -> {
                if (result != null) {
                    inputTo.setText(String.format("%.2f", result));
                } else {
                    showToast("Ошибка при конвертации валюты: Курс не найден");
                    inputTo.setText("");
                }
            }).execute();
        } catch (NumberFormatException e) {
            inputTo.setText("");
        }
    }

    /**
     * Проверяет доступность интернета.
     */
    private boolean isInternetAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Network network = connectivityManager.getActiveNetwork();
                if (network == null) return false;
                NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
                return capabilities != null &&
                        (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET));
            } else {
                // Для старых версий Android
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                return networkInfo != null && networkInfo.isConnected();
            }
        }
        return false;
    }

    /**
     * Показывает сообщение Toast.
     */
    private void showToast(String message) {
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
    }
}<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</androidx.constraintlayout.widget.ConstraintLayout><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraint_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:background="@color/background_color"
    tools:context=".MainActivity">

    <!-- Загрузочный индикатор (ProgressBar) -->
    <ProgressBar
        android:id="@+id/loading_indicator"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminateTint="@color/colorPrimary"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!-- Спиннеры выбора валют -->
    <Spinner
        android:id="@+id/spinner_from"
        style="@style/SpinnerStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toStartOf="@+id/button_swap"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!-- Кнопка для свапа валют с улучшенной стилизацией -->
    <com.google.android.material.button.MaterialButton
        android:id="@+id/button_swap"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        app:cornerRadius="24dp"
        app:backgroundTint="@color/colorPrimary"
        app:icon="@drawable/baseline_swap_horiz"
        app:iconTint="@android:color/white"
        app:iconGravity="start"
        app:rippleColor="@color/colorPrimaryDark"
        android:elevation="4dp"
        android:contentDescription="Поменять местами валюты"
        app:layout_constraintStart_toEndOf="@id/spinner_from"
        app:layout_constraintEnd_toStartOf="@id/spinner_to"
        app:layout_constraintTop_toTopOf="@id/spinner_from" />

    <Spinner
        android:id="@+id/spinner_to"
        style="@style/SpinnerStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toEndOf="@id/button_swap"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@id/spinner_from" />

    <!-- Поле ввода суммы -->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/input_layout_from"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Введите сумму"
        app:boxStrokeColor="@color/colorPrimary"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/spinner_from">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/input_from"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal"
            android:padding="12dp" />

    </com.google.android.material.textfield.TextInputLayout>

    <!-- Поле вывода конвертированной суммы -->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/input_layout_to"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Конвертированная сумма"
        app:boxStrokeColor="@color/colorPrimary"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/input_layout_from">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/input_to"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="none"
            android:focusable="false"
            android:padding="12dp"
            android:background="@drawable/edittext_background_disabled" />

    </com.google.android.material.textfield.TextInputLayout>

    <!-- Layout for Time Range Selection -->
    <LinearLayout
        android:id="@+id/time_range_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toBottomOf="@id/input_layout_to"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

        <TextView
            android:id="@+id/time_range_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Период:"
            android:textSize="16sp"
            android:layout_marginEnd="8dp"
            android:textColor="@color/black" />

        <!-- Заменяем Spinner на MaterialButtonToggleGroup -->
        <com.google.android.material.button.MaterialButtonToggleGroup
            android:id="@+id/time_range_toggle_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:singleSelection="true"> <!-- Добавьте этот атрибут -->

            <com.google.android.material.button.MaterialButton
                android:id="@+id/button_7_days"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="7 дней"
                android:checked="true"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/button_30_days"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="30 дней"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/button_90_days"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="90 дней"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton" />

        </com.google.android.material.button.MaterialButtonToggleGroup>
    </LinearLayout>

    <!-- График LineChart -->
    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/line_chart"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@color/chart_background"
        android:elevation="4dp"
        android:layout_marginTop="24dp"
        android:layout_marginBottom="16dp"
        app:layout_constraintTop_toBottomOf="@id/time_range_layout"
        app:layout_constraintBottom_toTopOf="@id/button_show_chart"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <!-- Кнопка для перехода к графику -->
    <com.google.android.material.button.MaterialButton
        android:id="@+id/button_show_chart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Показать график"
        app:cornerRadius="8dp"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toBottomOf="@id/line_chart"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout> исправь ошибки и перенеси график с выбором периода из mainActivity в chart_activity а также добавь в chart_activity возможность выбора валют для графика