package com.example.myapplication.api;

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 CurrencyRepository repository;
    private final Callback callback;

    public interface Callback {
        void onRatesLoaded();

        void onError(Exception e);
    }

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

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            repository.clearAllRates();

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

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

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

            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);
        }
    }
} сделать так чтобы если нет подключения к интернету брало данные из бд а если есть то тогда обновляло