/**
 * Init Request event
 * @module tracker/events/init-request
 */
const debug = require('debug')('bhit:tracker');
const moment = require('moment-timezone');
const WError = require('verror').WError;

/**
 * Init Request event class
 */
class InitRequest {
    /**
     * Create service
     * @param {App} app                         The application
     * @param {object} config                   Configuration
     * @param {Logger} logger                   Logger service
     * @param {Emailer} emailer                 Emailer
     * @param {Util} util                       Util
     * @param {UserRepository} userRepo         User repository
     */
    constructor(app, config, logger, emailer, util, userRepo) {
        this._app = app;
        this._config = config;
        this._logger = logger;
        this._emailer = emailer;
        this._util = util;
        this._userRepo = userRepo;
    }

    /**
     * Service name is 'modules.tracker.events.initRequest'
     * @type {string}
     */
    static get provides() {
        return 'modules.tracker.events.initRequest';
    }

    /**
     * Dependencies as constructor arguments
     * @type {string[]}
     */
    static get requires() {
        return [ 'app', 'config', 'logger', 'emailer', 'util', 'repositories.user' ];
    }

    /**
     * Event handler
     * @param {string} id           ID of the client
     * @param {object} message      The message
     */
    handle(id, message) {
        let client = this.tracker.clients.get(id);
        if (!client)
            return;

        debug(`Got INIT REQUEST from ${client.socket.remoteAddress}:${client.socket.remotePort}`);
        this._userRepo.findByEmail(message.initRequest.email)
            .then(users => {
                if (users.length) {
                    let response = this.tracker.InitResponse.create({
                        response: this.tracker.InitResponse.Result.EMAIL_EXISTS,
                    });
                    let reply = this.tracker.ServerMessage.create({
                        type: this.tracker.ServerMessage.Type.INIT_RESPONSE,
                        messageId: message.messageId,
                        initResponse: response,
                    });
                    let data = this.tracker.ServerMessage.encode(reply).finish();
                    debug(`Sending INIT RESPONSE to ${client.socket.remoteAddress}:${client.socket.remotePort}`);
                    return this.tracker.send(id, data);
                }

                let user = this._userRepo.create();
                user.name = null;
                user.email = message.initRequest.email;
                user.token = this.tracker.generateToken();
                user.confirm = this.tracker.generateToken();
                user.password = this._util.encryptPassword(this._util.generatePassword());
                user.createdAt = moment();
                user.confirmedAt = null;
                user.blockedAt = null;

                return this._userRepo.save(user)
                    .then(userId => {
                        if (!userId)
                            throw new Error('Could not create user');

                        return user;
                    });
            })
            .then(user => {
                let emailText = 'Breedhub Interconnect\n\n' +
                    'Someone has requested account creation on behalf of ' + user.email + '.\n\n' +
                    'If this was you then please run the following command on the daemon:\n\n' +
                    'bhid confirm ' + user.confirm;

                return this._emailer.send({
                        to: user.email,
                        from: this._config.get('email.from'),
                        subject: 'Please confirm account creation',
                        text: emailText,
                    })
                    .then(() => {
                        let response = this.tracker.InitResponse.create({
                            response: this.tracker.InitResponse.Result.ACCEPTED,
                        });
                        let reply = this.tracker.ServerMessage.create({
                            type: this.tracker.ServerMessage.Type.INIT_RESPONSE,
                            messageId: message.messageId,
                            initResponse: response,
                        });
                        let data = this.tracker.ServerMessage.encode(reply).finish();
                        debug(`Sending INIT RESPONSE to ${client.socket.remoteAddress}:${client.socket.remotePort}`);
                        this.tracker.send(id, data);
                    });
            })
            .catch(error => {
                this._logger.error(new WError(error, 'InitRequest.handle()'));
            });
    }

    /**
     * Retrieve server
     * @return {Tracker}
     */
    get tracker() {
        if (this._tracker)
            return this._tracker;
        this._tracker = this._app.get('servers').get('tracker');
        return this._tracker;
    }
}

module.exports = InitRequest;
@@ -3170,46 +3170,8 @@
 r');
-%0A%0A                        return user;
 %0A   
@@ -3181,33 +3181,32 @@
               %7D)
-;
 %0A            %7D)%0A
@@ -3191,38 +3191,32 @@
     %7D)%0A         
-   %7D)%0A
             .the
@@ -3214,25 +3214,30 @@
     
- 
 .then(
-user
+()
  =%3E %7B%0A
+        
     
@@ -3314,16 +3314,24 @@
         
+        
 'Someone
@@ -3422,16 +3422,24 @@
         
+       
+ 
 'If this
@@ -3527,16 +3527,24 @@
         
+        
 'bhid co
@@ -3576,32 +3576,40 @@
                 
+      
+  
 return this._ema
@@ -3644,16 +3644,20 @@
         
+    
 to: user
@@ -3688,16 +3688,20 @@
         
+  
+  
 from: th
@@ -3730,16 +3730,20 @@
 from'),%0A
+    
         
@@ -3826,16 +3826,20 @@
         
+ 
+   
 text: em
@@ -3859,35 +3859,47 @@
                 
-%7D)%0A
+    %7D)%0A        
                 
@@ -3932,32 +3932,40 @@
                 
+        
 let response = t
@@ -3990,32 +3990,40 @@
 sponse.create(%7B%0A
+        
                 
@@ -4103,36 +4103,50 @@
                 
-%7D);%0A
+        %7D);%0A      
                 
@@ -4145,32 +4145,34 @@
                 
+  
 let reply = this
@@ -4195,32 +4195,40 @@
 essage.create(%7B%0A
+        
                 
@@ -4312,32 +4312,40 @@
                 
+     
+   
 messageId: messa
@@ -4378,32 +4378,40 @@
                 
+        
 initResponse: re
@@ -4434,36 +4434,52 @@
                 
+    
-%7D);%0A
+    %7D);%0A        
                 
@@ -4564,32 +4564,40 @@
                 
+   
+     
 debug(%60Sending I
@@ -4694,24 +4694,32 @@
             
+        
 this.tracker
@@ -4727,32 +4727,64 @@
 send(id, data);%0A
+                            %7D);%0A
                 

send email after reject fixed