import request from 'request';
import {Observable} from 'rxjs';
import fs from 'fs';

const githubSearchQuery = `
  https://api.github.com/search/repositories?q=cycle+OR+cyclejs+language%3AJavaScript+created%3A>2014-11-01+stars%3A>3&type=Repositories&sort=stars&order=desc
`;

const requestOptions = {
  url: githubSearchQuery,
  headers: {
    'User-Agent': 'cycle-ecosystem'
  }
};

Observable.bindCallback(request)(requestOptions)
  .map(([error, response]) => JSON.parse(response.body).items)
  .map(toMarkdown)
  .forEach(updateReadme);

function toMarkdown (searchResults) {
  return `
# cycle-ecosystem
What are the most popular libraries for Cycle.js?

| Name     | Description       | Stars |
| -------- | ----------------- | ------|
${searchResults.map(toMarkdownEntry).join('\n')}

Auto generated by update.js.

Last updated at ${new Date().toString()}.
`;
}

function toMarkdownEntry (result) {
  return `| [${result.full_name}](${result.html_url}) | ${result.description} | ${result.stargazers_count} |`;
}

function updateReadme (markdown) {
  fs.writeFile('./README.md', markdown);
}

import request from 'request';
import {Observable} from 'rxjs';
import fs from 'fs';

const githubSearchQuery = `cycle+OR+cyclejs+language%3AJavaScript+created%3A>2014-11-01+stars%3A>3&type=Repositories&sort=stars&order=desc`;

function githubApiSearch (query) {
  return `https://api.github.com/search/repositories?q=${query}`;
}

function githubSearch (query) {
  return `https://github.com/search?q=${query}`;
}

const requestOptions = {
  url: githubApiSearch(githubSearchQuery),
  headers: {
    'User-Agent': 'cycle-ecosystem'
  }
};

Observable.bindCallback(request)(requestOptions)
  .map(([error, response]) => JSON.parse(response.body).items)
  .map(toMarkdown)
  .forEach(updateReadme);

function toMarkdown (searchResults) {
  return `
# cycle-ecosystem
What are the most popular libraries for Cycle.js?

| Name     | Description       | Stars |
| -------- | ----------------- | ------|
${searchResults.map(toMarkdownEntry).join('\n')}

Auto generated by update.js by [searching Github](${githubSearch(githubSearchQuery)}).

Last updated at ${new Date().toString()}.
`;
}

function toMarkdownEntry (result) {
  return `| [${result.full_name}](${result.html_url}) | ${result.description} | ${result.stargazers_count} |`;
}

function updateReadme (markdown) {
  fs.writeFile('./README.md', markdown);
}

Include search query used to generate results