var superagent = require('superagent'),
  debug = require('debug')('liftie:webcams'),
  day = require('./tools/millis').day,
  limiter = require('./tools/limiter');

module.exports = fetch;
module.exports.interval = {
  active: day,
  inactive: Infinity
};

var limit = limiter(12, 'minute');  // 12 times a minute

function fetch(resort, fn) {
  var webcams;
  debug("Fetching webcams for %s", resort.id);
  if (!resort.ll || !process.env.WEBCAMS_DEV_ID) {
    if (resort.webcams && resort.webcams.length) {
      webcams = resort.webcams;
    }
    return process.nextTick(fn.bind(null, null, webcams));
  }
  limit(function(err) {
    if (err) {
      debug('webcams.travel API limit %s', resort.id);
      return fn(err);
    }
    superagent('http://api.webcams.travel/rest')
    .query({
      method: 'wct.webcams.list_nearby',
      devid: process.env.WEBCAMS_DEV_ID,
      lat: resort.ll[1],
      lng: resort.ll[0],
      radius: 2,
      unit: 'mi',
      per_page: 1,
      format: 'json'
    }).end(function (res) {
      if (!res.ok) {
        debug('Failed query webcams for:', resort.id, res.status);
        return fn(res.status);
      }
      debug('Webcams nearby %s:', resort.id, res.text);
      res = JSON.parse(res.text);
      if (res.status !== 'ok') {
        return fn(res.status);
      }
      if (!res.webcams.count) {
        if (resort.webcams && resort.webcams.length) {
          webcams = resort.webcams;
        }
        return fn(null, webcams);
      }
      res = res.webcams.webcam[0];
      res = {
        name: res.title,
        source: res.url,
        image: res.preview_url,
        notice: 'Webcam by <a href="http://webcams.travel" target="_blank">webcams.travel</a>',
        mobile: {
          name: res.title,
          source: res.url_mobile,
          image: res.preview_url,
          notice: 'Webcam by <a href="http://m.webcams.travel" target="_blank">webcams.travel</a>'
        }
      };
      fn(null, [res]);
    });
  });
}

@@ -1520,21 +1520,39 @@
 bcam
-%5B0%5D;%0A
+.map(function(res) %7B%0A  
       re
 s = 
@@ -1547,19 +1547,20 @@
       re
-s =
+turn
  %7B%0A     
@@ -1554,32 +1554,34 @@
 eturn %7B%0A        
+ 
+ 
 name: res.title,
@@ -1573,32 +1573,34 @@
 ame: res.title,%0A
+  
         source: 
@@ -1608,32 +1608,34 @@
 es.url,%0A        
+ 
+ 
 image: res.previ
@@ -1634,32 +1634,34 @@
 es.preview_url,%0A
+  
         notice: 
@@ -1740,16 +1740,18 @@
 l%3C/a%3E',%0A
+  
         
@@ -1762,32 +1762,34 @@
 le: %7B%0A          
+  
 name: res.title,
@@ -1781,32 +1781,34 @@
 ame: res.title,%0A
+  
           source
@@ -1827,32 +1827,34 @@
 bile,%0A          
+  
 image: res.previ
@@ -1853,32 +1853,34 @@
 es.preview_url,%0A
+  
           notice
@@ -1966,26 +1966,30 @@
 a%3E'%0A        
-%7D%0A
+  %7D%0A  
       %7D;%0A   
@@ -1985,16 +1985,26 @@
      %7D;%0A
+      %7D);%0A
       fn
@@ -2014,13 +2014,11 @@
 ll, 
-%5B
 res
-%5D
 );%0A 

allow for multiple webcams to be returned by the API