{"size": 1860, "ext": "js", "max_stars_repo_path": "src/test/a11y/request.js", "max_stars_repo_name": "mikeSmith08/htbhf-applicant-web-ui", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/a11y/request.js", "max_issues_repo_name": "mikeSmith08/htbhf-applicant-web-ui", "max_issues_repo_issues_event_min_datetime": "2019-01-10T15:56:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T08:13:00.000Z", "max_forks_repo_path": "src/test/a11y/request.js", "max_forks_repo_name": "mikeSmith08/htbhf-applicant-web-ui", "max_forks_repo_forks_event_min_datetime": "2019-12-13T16:17:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-24T14:40:29.000Z"}
{"max_stars_count": null, "max_issues_count": 238, "max_forks_count": 4, "avg_line_length": 18.2352941176, "max_line_length": 86, "alphanum_fraction": 0.5301075269}
'use strict'

const request = require('request')

const getSIDCookie = response => {
  const value = response.headers['set-cookie'].toString().match('htbhf.sid=(.*?);')[1]
  return {
    key: 'htbhf.sid',
    value: value
  }
}

const getCSRFToken = body => body.match('"_csrf" value="(.*)"')[1]

const getSIDCookieAndCSRFToken = (url) =>
  new Promise((resolve, reject) => {
    const options = {
      url
    }

    request(options, (error, response, body) => {
      if (error) {
        return reject(error)
      }

      const cookie = getSIDCookie(response)
      resolve({
        requestCookie: `${cookie.key}=${cookie.value}`,
        csrfToken: getCSRFToken(body)
      })
    })
  })

const postFormData = (url, form, cookie) =>
  new Promise((resolve, reject) => {
    request.post({
      url,
      form,
      headers: {
        Cookie: cookie
      }
    }, (error) => {
      if (error) {
        return reject(error)
      }

      resolve()
    })
  })

const get = (url, cookie) =>
  new Promise((resolve, reject) => {
    request.get({
      url,
      headers: {
        Cookie: cookie
      }
    }, (error, httpResponse, body) => {
      if (error) {
        return reject(error)
      }

      resolve(body)
    })
  })

const postJsonData = (url, body) =>
  new Promise((resolve, reject) => {
    request.post({
      url,
      body,
      headers: {
        'Content-Type': 'application/json'
      }
    }, (error, httpResponse, body) => {
      if (error) {
        return reject(error)
      }

      resolve(body)
    })
  })

const performDelete = (url) =>
  new Promise((resolve, reject) => {
    request.delete({ url }, (error) => {
      if (error) {
        return reject(error)
      }

      resolve()
    })
  })

module.exports = {
  getSIDCookieAndCSRFToken,
  postFormData,
  postJsonData,
  performDelete,
  get
}
