'use strict';

const config = require('../../src/config');

const requestPromised = require('../utils/request-promised');


function getStateRepresentatives(addressStr) {
  const url = _buildRepsUrl(config.apiKeys.googleCivicInfoApi, addressStr);

  return requestPromised({
    method: 'GET',
    url,
    headers: {
      'Accept': 'application/json'
    }
  })
  .then((response) => {
    console.log(response.body);

    // TODO parse response.body ...
    // return array of *state* representatives

  });
}


function _buildRepsUrl(apiKey, addressStr) {
  addressStr = encodeURIComponent(addressStr);
  return `https://www.googleapis.com/civicinfo/v2/representatives?key=${apiKey}&address=${addressStr}`;
}


module.exports = {
  getStateRepresentatives
};

@@ -351,16 +351,32 @@
 n'%0A    %7D
+,%0A    json: true
 %0A  %7D)%0A  
@@ -405,120 +405,45 @@
     
-console.log(response.body);%0A%0A    // TODO parse response.body ...%0A    // return array of *state* representatives%0A
+return _parseRepsData(response.body);
 %0A  %7D
@@ -649,16 +649,966 @@
 %7D%60;%0A%7D%0A%0A%0A
+function _parseRepsData(data) %7B%0A  try %7B%0A    const %7B offices, officials %7D = data;%0A%0A    const reps = %5B%5D;%0A%0A    // find %60sldl%60 (lower state legislature)%0A    // and %60sldu%60 (upper state legislature) offices%0A    for (let officeInd = 0; officeInd %3C offices.length; officeInd++) %7B%0A      const office = offices%5BofficeInd%5D;%0A      // %60divisionId%60 is e.g. %22ocd-division/country:us/state:ca/sldl:15%22%0A      if (/%5C/sld%5Blu%5D:/.test(office.divisionId)) %7B%0A        const %7BofficialIndices%7D = office;%0A        for (let j = 0; j %3C officialIndices; j++) %7B%0A          const officialIndex = officialIndices%5Bj%5D;%0A          const official = officials%5BofficialIndex%5D;%0A          if (official) %7B%0A            reps.push(%0A              Object.assign(%7B%0A                office: office.name%0A              %7D, official)%0A            );%0A          %7D%0A        %7D%0A      %7D%0A    %7D%0A    return reps;%0A%0A  %7D catch (err) %7B%0A    console.error('Failed to parse representative data', err);%0A    return %5B%5D;%0A  %7D%0A%7D%0A%0A%0A
 module.e
@@ -1643,12 +1643,47 @@
 ntatives
+,%0A  _buildRepsUrl,%0A  _parseRepsData
 %0A%7D;%0A

parse civic info response