const fs = require('fs');
const Logger = require('./logger');
const ShortId = require('shortid');

const ATTACHMENT_STORE = '../images';
const ATTACHMENT_STORE_PROFILE = '/profile';
const ATTACHMENT_STORE_MESSAGE = '/message';
const ATTACHMENT_SUFFIX_DETAIL = '_detail';
const ATTACHMENT_SUFFIX_THUMBNAIL = '_thumbnail';

function generateFilename (filename, type = 'detail') {
  var re = /(?:\.([^.]+))?$/;
  var ext = re.exec(filename)[1];
  return '' + ShortId.generate() + (type === 'thumbnail' ? ATTACHMENT_SUFFIX_THUMBNAIL : ATTACHMENT_SUFFIX_DETAIL) + "." + ext;
}

function processImage (data, context, type, callback) {
  var folder = ATTACHMENT_STORE + (context === 'profile' ? ATTACHMENT_STORE_PROFILE : ATTACHMENT_STORE_MESSAGE);
  var filename = generateFilename(data.imageFilename, type);

  var dataUrl = data.image;
  var matches = dataUrl.match(/^data:.+\/(.+);base64,(.*)$/);
  var base64Data = matches[2];
  var buffer = new Buffer(base64Data, 'base64');
  
  saveImage(folder + '/' + filename, buffer, callback);
}

function saveImage (filename, data, callback = noop) {
  fs.writeFile(filename, data, function (err, stat) {
    if (err) {
      Logger.error('[Images.saveImage] Image save failure.', { err: err, stat: stat, filename: filename });
      callback(err, null);
    } else {
      Logger.debug('[Images.saveImage] Image save successful.', { stat: stat, filename: filename });
      callback(null, filename.substring(2));
    }
  });
}

function noop (err, result) {
  Logger.debug('No callback function supplied.', { err: err, result: result });
}

module.exports = {

  save: (data, filename, callback = noop) => {
    saveImage(filename, data, callback);
  },
   
  saveMessageImage: (data, callback) => {
    processImage(data, 'message', 'detail', callback);
  },
  
  saveProfileDetailImage: (data, callback) => {
    processImage(data, 'profile', 'detail', callback);
  },
  
  saveProfileThumbnailImage: (data, callback) => {
    processImage(data, 'profile', 'thumbnail', callback);
  }
};

