#!/usr/bin/env coffee

fs = require('fs')
path = require('path')
_ = require('lodash')
request = require('sync-request')

kittenData = []

getImageUrl = (pet) ->
  return null unless pet.media?.photos?
  for photo in pet.media.photos.photo
    return photo.$t if photo['@size'] == 'pn'
  return null
  
getDescription = (pet) ->
  raw = pet.description.$t || ""
  return raw.replace('\n\n', '<br><br>').replace('\n', '<br><br>')
      

# for a single request, petfinder api will return at most count=1000 results
FETCH_SIZE = 1000

# and for any given search criteria, you can only page upto 2000 results
ZIP_CODES = ['98108', "97201", "90291"]
# should give us 3K results


fetchForZip = (zipCode) ->
  url = "http://api.petfinder.com/pet.find?key=c6b4127cfc05b8cfb15a0575712c9166" + 
    "&format=json&location=#{zipCode}&age=baby&animal=cat" +
    "&count=#{FETCH_SIZE}"
  console.log "fetching for #{zipCode}"
  res = request "GET", url
  body = JSON.parse(res.getBody('utf8'))
  
  return unless body.petfinder.pets?   # ran out of data?
    
  console.log "got #{body.petfinder.pets.pet.length} kittens"
  for pet in body.petfinder.pets.pet
    kittenData.push {
      id: pet.id.$t
      name: pet.name.$t
      breed: pet.breeds.breed.$t
      adoptable: pet.status.$t == "A"
      contactEmail: pet.contact.email.$t
      contactCity: pet.contact.city.$t
      description: getDescription(pet)
      sex: pet.sex.$t
      size: pet.size.$t
      imageUrl: getImageUrl(pet)
      lastUpdate: pet.lastUpdate.$t
      shelterId: pet.shelterId.$t
      petfinderUrl: "https://www.petfinder.com/petdetail/#{pet.id.$t}"
    }
  

fetchForZip(zip) for zip in ZIP_CODES

console.log "saving #{kittenData.length} kittens"
fs.writeFileSync "./test/lib/kittenData.js", """

// this file is generated by scripts/fetchKittenData
// works from script tag or from nodejs require for testing

var _KITTEN_DATA = #{JSON.stringify(kittenData, null, "  ")};

if (window !== 'undefined') {
  window.KITTEN_DATA = _KITTEN_DATA;
} else if (typeof module !== 'undefined' && module.exports) {
  module.exports = _KITTEN_DATA;
} else { 
  KITTEN_DATA = _KITTEN_DATA;
}
"""



  


