import { fetchJsonp } from './fetch';
import moment from 'moment';

// ********* SECURITY APIS ********* //

// Fetch quote from data endpoint
export function fetchQuote(symbol) {
  return fetchJsonp('https://data.benzinga.com/rest/v2/quote?symbols=' + symbol, {
    headers: {'accept': 'application/json'},
    method: 'get'
  })
  .then(resp => resp.json())
  .then(data => data[symbol]);
}

// Fetch financials from data endpoint
export function fetchFinancials(symbol) {
  const date = moment().subtract(12, 'months').format('YYYY-MM-DD');
  return fetchJsonp('https://data.benzinga.com/rest/v3/fundamentals?symbols=' + symbol + '&period=3M' + '&asOf=' + date, {
    headers: {'accept': 'application/json'},
    method: 'get'
  })
  .then(resp => resp.json())
  .then(data => data.result[0]);
}

// Fetch averages from data endpoint
export function fetchAverages(symbol) {
  return fetchJsonp(' https://data.benzinga.com/rest/v3/tickerDetail?symbols=' + symbol, {
    headers: {'accept': 'application/json'},
    method: 'get'
  })
  .then(resp => resp.json())
  .then(data => data.result[0]);
}

// Fetch ownership from data endpoint
export function fetchOwnership(symbol) {
  return fetchJsonp('https://data.benzinga.com/rest/v3/ownership/summary?symbols=' + symbol, {
    headers: {'accept': 'application/json'},
    method: 'get'
  })
  .then(resp => resp.json())
  .then(data => data.result[0].summary[0])
  .catch(err => reject(err));
}

// Fetch chart points
export function fetchChart(symbol, period = '1d') {
  let interval = '1m';
  switch (period) {
  case '5y':
    interval = '1w';
    break;
  case 'YTD':
  case '3m':
    interval = '1d';
    break;
  case '1m':
    interval = '1h';
    break;
  case '5d':
    interval = '5m';
    break;
  case '1d':
  default:
    interval = '1m';
    break;
  }
  return fetchJsonp('https://data.benzinga.com/rest/v2/chart?symbol=' + symbol + '&from=' + period + '&interval=' + interval, {
    headers: {'accept': 'application/json'},
    method: 'get'
  })
  .then(resp => resp.json())
  .then(data => data.candles);
}

// Fetch corporate logo
export function fetchCorporateLogo(symbol) {
  const token = 'bcb21f0e5c2ec60fc1fa834444cf04665e04175a6e860cd5d27c9f25e31808d1';
  const url = 'https://api.benzinga.com/api/v1/logos';
  const query = '?token=' + token + '&symbols=' + symbol;
  return fetch(url + query, {
    headers: {'accept': 'application/json'},
    method: 'get'
  })
  .then(resp => resp.json())
  .then(data => data.logos[0].files.original);
}
