const webhookService = require('../webhook/webhook-service');
const Uuid = require('uuid');
const set = require('lodash/set');
const allowedImageMimes = require('../image/allowed-image-mimes');

// e.g. convert { foo.bar: 'baz' } to { foo: { bar: 'baz' }}
const expandDotPaths = function(object) {
  Object.keys(object).forEach(key => {
    if (key.indexOf('.') > -1) {
      const value = object[key];
      delete(object[key]);
      set(object, key, value);
    }
  });
  return object;
};

module.exports = (userService, imageService) => {
  return {
    async updateUserProfile(user, requestPayload) {
      let profile = user.get('profile');
      const { shouldClearPicture, ...originalPayload } = requestPayload;
      const payload = expandDotPaths(originalPayload);

      const oldPicture = profile.picture;
      const pictureMIME = originalPayload.picture
        ? originalPayload.picture.hapi.headers['content-type']
        : null;

      if (allowedImageMimes.indexOf(pictureMIME) >= 0) {
        const uuid = Uuid();
        const bucket = uuid.substring(0, 2);
        const filename = await imageService.uploadImageStream(originalPayload.picture, `pictures/${bucket}/${uuid}`);

        profile = Object.assign(profile, payload, { picture: filename });
      } else {
        delete originalPayload.picture;
        if (shouldClearPicture) {
          profile = Object.assign(profile, payload, {picture: null});
        } else {
          profile = Object.assign(profile, payload);
        }
      }

      user = await userService.update(user.get('id'), { profile });
      webhookService.trigger('user.update', user);

      if (oldPicture) {
        await imageService.deleteImage(oldPicture.replace(/^.*\/\/[^\/]+\//, ''));
      }

      return user;
    },

  };
};

module.exports['@singleton'] = true;
module.exports['@require'] = [
  'user/user-service',
  'image/image-service',
];

@@ -774,50 +774,8 @@
 );%0A%0A
-      const oldPicture = profile.picture;%0A
     
@@ -820,16 +820,16 @@
 picture%0A
+
         
@@ -982,15 +982,22 @@
 d = 
-Uuid();
+user.get('id')
 %0A   
@@ -1312,32 +1312,169 @@
 ClearPicture) %7B%0A
+          if (payload.picture) %7B%0A            await imageService.deleteImage(payload.picture.replace(/%5E.*%5C/%5C/%5B%5E%5C/%5D+%5C//, ''));%0A          %7D%0A
           profil
@@ -1680,24 +1680,24 @@
 profile %7D);%0A
+
       webhoo
@@ -1740,124 +1740,8 @@
 );%0A%0A
-      if (oldPicture) %7B%0A        await imageService.deleteImage(oldPicture.replace(/%5E.*%5C/%5C/%5B%5E%5C/%5D+%5C//, ''));%0A      %7D%0A%0A
     

use uuid for picture name in api endpoint