package com.example.myapplication;

import android.content.Context;

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;

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

    public void insertCurrencyRateSync(CurrencyRate rate) {
        currencyRateDao.insertCurrencyRate(rate);
    }

    public void clearAllRates() {
        currencyRateDao.clearAllRates();
    }

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

    // Добавляем метод для получения дат в заданном диапазоне
    public List<Date> getAllDatesWithinRange(Date startDate, Date endDate) {
        return currencyRateDao.getAllDatesWithinRange(startDate, endDate);
    }

    // Метод для получения исторических данных курса за заданный период
    public List<CurrencyRate> getCurrencyRateHistoryWithinDates(String baseCurrency, String targetCurrency, Date startDate, Date endDate) {
        return currencyRateDao.getCurrencyRateHistoryWithinDates(baseCurrency, targetCurrency, startDate, endDate);
    }

    public List<String> getAllUniqueCurrencies() {
        List<String> baseCurrencies = currencyRateDao.getAllBaseCurrencies();
        List<String> targetCurrencies = currencyRateDao.getAllTargetCurrencies();
        Set<String> allCurrencies = new HashSet<>(baseCurrencies);
        allCurrencies.addAll(targetCurrencies);
        return new ArrayList<>(allCurrencies);
    }

    public Double getExchangeRate(String fromCurrency, String toCurrency) {
        return currencyRateDao.getLatestExchangeRate(fromCurrency, toCurrency);
    }

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

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;

import com.example.myapplication.CurrencyRate;
import com.example.myapplication.CurrencyRepository;

import org.json.JSONObject;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

public class LoadCurrencyRatesTask extends AsyncTask<Void, Void, Void> {
    private static final String TAG = "LoadCurrencyRatesTask";
    private static final String API_KEY = "05ZPKFI7IKOPLLRM"; // Replace with your Alpha Vantage API key

    private final Context context;
    private final CurrencyRepository repository;
    private final Callback callback;

    public interface Callback {
        void onRatesLoaded();

        void onError(Exception e);
    }

    public LoadCurrencyRatesTask(Context context, CurrencyRepository repository, Callback callback) {
        this.context = context;
        this.repository = repository;
        this.callback = callback;
    }

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            // Check for internet connectivity
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

            if (networkInfo != null && networkInfo.isConnected()) {
                // Connected to the internet, proceed to fetch data
                Log.d(TAG, "Internet connection available. Updating rates from API.");

                // Clear existing rates in the repository
                repository.clearAllRates();

                List<String> currencies = Arrays.asList("EUR", "BYN", "RUB");

                for (String targetCurrency : currencies) {
                    fetchHistoricalRates("USD", targetCurrency);
                }

                if (callback != null) {
                    callback.onRatesLoaded();
                }
            } else {
                // No internet connection, use existing data from the database
                Log.d(TAG, "No internet connection. Using cached data from the database.");

                // No need to clear the rates; use existing data
                if (callback != null) {
                    callback.onRatesLoaded();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error loading currency rates", e);
            if (callback != null) {
                callback.onError(e);
            }
        }
        return null;
    }

    private void fetchHistoricalRates(String baseCurrency, String targetCurrency) {
        try {
            String apiUrl = String.format(
                    Locale.US,
                    "https://www.alphavantage.co/query?function=FX_DAILY&from_symbol=%s&to_symbol=%s&apikey=%s&outputsize=compact",
                    baseCurrency,
                    targetCurrency,
                    API_KEY
            );

            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();

            InputStream inputStream;
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inputStream = connection.getInputStream();
            } else {
                inputStream = connection.getErrorStream();
            }

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream)
            );
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            String jsonResponseString = response.toString();

            Log.d(TAG, "API Response for " + baseCurrency + "/" + targetCurrency + ": " + jsonResponseString);

            JSONObject jsonResponse = new JSONObject(jsonResponseString);

            if (jsonResponse.has("Error Message")) {
                Log.e(TAG, "Error fetching data for " + targetCurrency + ": " + jsonResponse.getString("Error Message"));
                return;
            }

            if (jsonResponse.has("Note")) {
                Log.e(TAG, "API call frequency limit reached: " + jsonResponse.getString("Note"));
                return;
            }

            if (!jsonResponse.has("Time Series FX (Daily)")) {
                Log.e(TAG, "Unexpected JSON format for currency: " + targetCurrency);
                return;
            }

            JSONObject timeSeries = jsonResponse.getJSONObject("Time Series FX (Daily)");

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

            Iterator<String> dates = timeSeries.keys();
            while (dates.hasNext()) {
                String dateStr = dates.next();
                JSONObject dailyData = timeSeries.getJSONObject(dateStr);

                double rate = dailyData.getDouble("4. close");

                Date date = dateFormat.parse(dateStr);

                CurrencyRate currencyRate = new CurrencyRate(baseCurrency, targetCurrency, rate, date);
                repository.insertCurrencyRateSync(currencyRate);

                double reverseRate = rate != 0 ? 1 / rate : 0;
                CurrencyRate reverseCurrencyRate = new CurrencyRate(targetCurrency, baseCurrency, reverseRate, date);
                repository.insertCurrencyRateSync(reverseCurrencyRate);
            }

            Log.d(TAG, "Historical rates fetched for " + baseCurrency + "/" + targetCurrency);

        } catch (JSONException e) {
            Log.e(TAG, "JSON parsing error for " + targetCurrency, e);
        } catch (Exception e) {
            Log.e(TAG, "Error fetching historical rates for " + targetCurrency, e);
        }
    }
} почини классы