import { validateURL } from '../utils/utils';
import 'isomorphic-fetch';

const getParticipatingOrganizations = (url) => {
  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) => {
              const orgs = data
                .map(org => ({ ...org, version: 'none' }))
                .sort((a, b) => a.name.localeCompare(b.name));

              resolve(orgs);
            })
            .catch(reject);
        })
        .catch((err) => {
          reject(err);
        })
    );
  }
};

export default getParticipatingOrganizations;
