import fetch from 'isomorphic-unfetch';
import parseResponseData from './parseResponseData';
import getStatus from './getStatus';
const fetchData = async function fetchData(currentValue) {
  const {
    config,
    metadata: originalMeta = {}
  } = currentValue;
  const {
    url,
    headers: configHeaders = {}
  } = config;
  const headers = {
    ...(configHeaders || {}),
    'If-Modified-Since': originalMeta.lastUpdatedHeader
  };
  try {
    const resp = await fetch(url, {
      headers
    });
    const statusCode = resp.status;
    const status = getStatus(statusCode);
    if (status === 'error') {
      let error;
      try {
        error = resp.text();
      } catch (e) {/* Ignore */}
      return {
        status,
        statusCode,
        error,
        value: currentValue
      };
    }
    if (status !== 'update') {
      return {
        status,
        statusCode,
        value: currentValue
      };
    }
    const newLastModifiedTime = resp.headers.get('last-modified');
    const contentType = resp.headers.get('content-type');
    const dataType = resp.headers.get('x-amz-meta-datatype');

    // If there is no `last-modified` header then `lastUpdatedHeader` will be
    // `null` and we'll use the current time as the `lastUpdated` and
    // `lastUpdatedTimestamp` values
    const lastUpdatedDate = newLastModifiedTime ? new Date(newLastModifiedTime) : new Date();
    return {
      status,
      statusCode,
      value: {
        config,
        metadata: {
          lastUpdatedHeader: newLastModifiedTime,
          lastUpdated: lastUpdatedDate.getTime(),
          lastUpdatedTimestamp: lastUpdatedDate.toISOString(),
          contentType,
          dataType: dataType ? JSON.parse(dataType) : null
        },
        data: await parseResponseData(resp)
      }
    };
  } catch (error) {
    return {
      status: 'error',
      statusCode: undefined,
      error,
      value: currentValue
    };
  }
};
export default fetchData;