var request = require('request');
var config = require('./config');
var crypto = require('crypto');
var tweet = require('./tweet');
var stringify = require('json-stable-stringify');
var PouchDB = require('pouchdb');
var Promise = require('bluebird');
var db = new PouchDB('./local');
var params = {
  qs: {
    api_key: config.key
  },
  url: 'http://realtime.mbta.com/developer/api/v2/alerts',
  json: true
};

function defaultCallback(err) {
  if (err) {
    return console.log(err);
  }
}



function filterEl(headerText) {
  return /elevator/.test(headerText.toLowerCase()) || /escalator/.test(headerText.toLowerCase());
}

function eachAlert(alert) {
  var nParams;
  if (filterEl(alert.header_text)) {
    return;
  }
  alert._id = alert.alert_id.toString();
  var newAlert = false;
  return db.get(alert._id).then(function (doc) {
    alert._rev = doc._rev;
    if(stringify(alert) !== stringify(doc)) {
      return alert;
    }
  }, function () {
    newAlert = true;
    return alert;
  }).then(function (alert) {
    if (alert) {
      return db.put(alert);
    }
  }).then(function (resp) {
    if (newAlert) {
      tweet(alert);
    }
  });
}

var lastHash = false;
function makeHash(obj) {
  var hash = crypto.createHash('sha512');
  hash.update(stringify(obj));
  return hash.digest('base64');
}
function dumbCache(alerts) {
  var newHash = makeHash(alerts);
  if (lastHash === newHash) {
    //console.log('no change');
    return false;
  } else {
    lastHash = newHash;
    return true;
  }
}

function start() {
  request(params, function(e, r, b) {
     if(e) {
      lastHash = false;
      console.log(e.stack);
      console.log(e);
      process.exit(1);
    } else if (b && b.alerts) {
      if (dumbCache(b.alerts)) {
        return Promise.all(b.alerts.map(eachAlert)).then(function () {
           process.send({
            ok: true
          });
        }).catch(function (e) {
          console.log(e.stack);
          console.log(e);
          process.exit(1);
        });
      }
      process.send({
        ok: true
      });
      return;
    }
  });
}

module.exports = start;
@@ -941,28 +941,216 @@
 , function (
+e
 ) %7B%0A
+    if (e.message === 'deleted') %7B%0A      return db.allDocs(%7Bkeys:%5Balert._id%5D%7D).then(function (a)%7B%0A        alert._rev = a.rows%5B0%5D.value.rev;%0A        return alert;%0A      %7D);%0A    %7D else %7B%0A  
     newAlert
@@ -1158,16 +1158,18 @@
 = true;%0A
+  
     retu
@@ -1178,16 +1178,22 @@
  alert;%0A
+    %7D%0A
   %7D).the

deal with deleted docs