'use strict';

const grayMethods = require('cmnjs/color/convert/rgbToGray');
const chalk = require('chalk');
const fancyLog = require('fancy-log');
const extend = require('cmnjs/object/extend/deep');
const fileType = require('file-type');
const isBuffer = require('is-buffer');
const readChunk = require('read-chunk');
const md5 = require('md5');

const defaults = require('./defaults');
const splitPath = require('./splitPath');
const getPath = require('./getPath');
const packageJson = require('../package.json');

const moduleName = packageJson.name;
const version = packageJson.version;
const bytesOfBufferToCheckFileType = 262;


function prepareOptionsStart(file, options, startTime) {

  var filePath = getPath(file);

  if (typeof options !== 'object') {
    options = {};
  }

  // extend defaults
  options = extend({}, defaults, options);

  // file name and path
  options.fileName = filePath.split('/').pop();
  if (!options.bufferMode) {
    options.path = splitPath(filePath);
  }

  // prepare log
  if (!options.log) {
    options.log = fancyLog;
  }
  options.log = options.log.bind(options.log,
    chalk.yellow(options.logName ? options.logName : moduleName + '@' + version)
  );

  // prepare algorithm
  if (typeof options.algorithm !== 'function') {
    options.algorithm = grayMethods[options.algorithm];
  }

  options.startTime = startTime;
  options.file = file;

  return options;

}

function prepareOptionsEnd(fileData) {

  var buffer;
  var file = fileData.file;

  if (!isBuffer(file)) {
    buffer = readChunk.sync(file, 0, bytesOfBufferToCheckFileType);
  } else {
    buffer = file;
  }

  // extend fileData with file info
  extend(fileData, fileType(buffer));

  if (fileData.mime) {
    // fileData.pixelsHandling = fileData.mime === 'image/gif' ? 'gif' : 'png';
    fileData.pixelsHandling = fileData.mime.split('/')[1];
  }

  if (!fileData.fileName) {
    fileData.fileName = md5(file) + '.' + fileData.ext;
  }

  // more log extend
  fileData.log = fileData.log.bind(fileData.log, chalk.blue(fileData.fileName));

  return fileData;

}

module.exports = {
  start: prepareOptionsStart,
  end: prepareOptionsEnd
};
