/*!
 * Copyright (c) 2021 Eclipse Foundation, Inc.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * Contributors:
 *   Eric Poirier <eric.poirier@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import $, { type } from 'jquery';
import parse from 'parse-link-header';
import { validateURL } from '../utils/utils';
import 'isomorphic-fetch';

const getNewsData = (url, news = []) => {
  if (validateURL(url)) {
    return new Promise((resolve, reject) =>
      fetch(url)
        .then((response) => {
          if (response.status !== 200) {
            throw `${response.status}: ${response.statusText}`;
          }
          response
            .json()
            .then((data) => {
              news = news.concat(data.news);
              const linkHeader = parse(response.headers.get('Link'));
              if (linkHeader?.next && typeof linkHeader.next?.url === 'string') {
                getNewsData(linkHeader.next.url, news).then(resolve).catch(reject);
              } else {
                news.sort((a, b) => a.title.localeCompare(b.title));
                resolve(news);
              }
            })
            .catch(reject);
        })
        .catch((err) => {
          reject(err);
        })
    );
  }
};

export default getNewsData;
