import React, {useState} from 'react';
import {Counter} from './counter';
import {useInterval} from './use_interval';
import {determineBaseUrl} from './base_url';

export function CampaignTotals(props) {
  const {donateProccessorFallbackUrl, counters} = props;
  const donateProccessorBaseUrl = determineBaseUrl(donateProccessorFallbackUrl);
  const [amounts, setAmounts] = useState({
    'totalDonations': 0,
    'totalAmount': 0,
    'amountWithMozilla': 0
  });

  const requestTotal = async () => {
    const options = {
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'GET',
    };
    const response = await fetch(`${donateProccessorBaseUrl}/campaign-totals`, options);
    const response_data = await response.json();
    if ('errors' in response_data) {
      if (response_data['errors'].length > 0) {
        console.log(`Error fetching campaign totals from ${donateProccessorBaseUrl}/campaign-totals`, response_data);
      } else {
        setAmounts(response_data['data']);
      }
    }
  };

  useInterval(requestTotal, 5000, true);

  function renderCounters(item) {
    return (
      <Counter
        key={item.cssClass}
        cssClass={item.cssClass}
        label={item.label}
        amount={amounts[item.field]}
      />
    );
  }

  return (
    <React.Fragment>
      {counters.map((item) => renderCounters(item))}
    </React.Fragment>
  );
}
