'use strict';
import Agenda from 'agenda';
import config from 'config';
import logger from '@hoist/logger';
import {
  Publisher
}
from '@hoist/broker';
import {
  Event,
  EventMetric,
  _mongoose
}
from '@hoist/model';
import Moment from 'moment';
import uuid from 'uuid';
import Bluebird from 'bluebird';

Bluebird.promisifyAll(_mongoose);

class Runner {
  constructor() {
    this._publisher = new Publisher();
    this._logger = logger.child({
      cls: this.constructor.name
    });

  }
  processEvents(job, done) {
    this._logger.info({
      job: job
    }, 'processing schedule job');
    var data = job.attrs.data;
    return Promise.resolve()
      .then(() => {
        Promise.all(data.events.map((eventName) => {
          return this.createEvent(data, eventName);
        }));
      }).then(() => {
        done();
      }).catch((err) => {
        this._logger.error(err);
        done(err);
      });
  }
  createEvent(data, eventName) {
    var ev = new Event({
      eventId: uuid.v4().split('-').join(''),
      applicationId: data.application,
      eventName: eventName,
      environment: data.environment,
      correlationId: require('uuid').v4()
    });

    this._logger.info({
      eventId: ev.messageId,
      applicationId: ev.applicationId,
      correlationId: ev.correlationId,
      eventName: eventName
    }, 'raising scheduled event');
    return this._publisher.publish(ev)
      .then(() => {
        var raisedDate = new Moment();
        var update = {
          $inc: {}
        };
        update.$inc.totalRaised = 1;
        update.$inc['raised.' + raisedDate.utc().minutes()] = 1;
        EventMetric.updateAsync({
          application: ev.applicationId,
          environment: 'live',
          eventName: ev.eventName,
          timestampHour: raisedDate.utc().startOf('hour').toDate()
        }, update, {
          upsert: true
        }).catch((err) => {
          this._logger.alert(err);
          this._logger.error(err);
        });
        return ev;
      })
      .catch((err) => {
        err.eventName = eventName;
        this._logger.error(err, 'unable to publish event');
        this._logger.alert(err, data.application, {
          source: 'Runner#createEvent',
          eventName: eventName
        });
      });
  }
  start() {
    return _mongoose.connectAsync(config.get('Hoist.mongo.core.connectionString')).
    then(() => {
      logger.info('creating agenda');
      this._agenda = new Agenda({
        db: {
          address: config.get('Hoist.mongo.core.connectionString')
        }
      });
      logger.info('promisifying agenda');
      Bluebird.promisifyAll(this._agenda);
      logger.info('defining job');
      this._agenda.define('create:event2', (job, done) => {
        return this.processEvents(job, done);
      });
      return Bluebird.delay(1000);
    }).then(() => {
      logger.info('starting agenda');
      this._agenda.start();
      logger.info('waiting on schedule');

    });

  }
  stop() {
    return this._agenda.stopAsync().then(() => {
      delete this._agenda;
      return _mongoose.disconnectAsync();
    });
  }
}


export default Runner;

@@ -301,16 +301,56 @@
 ebird';%0A
+import %7B%0A  MongoClient%0A%7D from 'mongodb';
 %0ABluebir
@@ -2466,32 +2466,74 @@
 ating agenda');%0A
+      return new Promise((resolve) =%3E %7B%0A  
       this._agen
@@ -2562,14 +2562,18 @@
     
+  
 db: %7B%0A
+  
     
@@ -2643,24 +2643,26 @@
         
+  
 %7D%0A      
 %7D);%0A    
@@ -2649,28 +2649,94 @@
     %7D%0A      
-%7D);%0A
+  %7D, () =%3E %7B%0A          resolve();%0A        %7D);%0A      %7D).then(() =%3E %7B%0A  
       logger
@@ -2771,16 +2771,18 @@
 ;%0A      
+  
 Bluebird
@@ -2808,32 +2808,34 @@
 _agenda);%0A      
+  
 logger.info('def
@@ -2845,32 +2845,34 @@
 ng job');%0A      
+ 
+ 
 this._agenda.def
@@ -2909,32 +2909,34 @@
 e) =%3E %7B%0A        
+  
 return this.proc
@@ -2953,24 +2953,26 @@
 job, done);%0A
+  
       %7D);%0A  
@@ -2979,34 +2979,9 @@
     
-return Bluebird.delay(1000
+%7D
 );%0A 

fix agenda promise