{"size": 1261, "ext": "js", "max_stars_repo_path": "lib/imageOptimizer.js", "max_stars_repo_name": "fu4303/static-photo-gallery", "max_stars_repo_stars_event_min_datetime": "2017-03-07T18:46:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-17T18:38:17.000Z", "max_issues_repo_path": "lib/imageOptimizer.js", "max_issues_repo_name": "fu4303/static-photo-gallery", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/imageOptimizer.js", "max_forks_repo_name": "fu4303/static-photo-gallery", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 4, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.829787234, "max_line_length": 82, "alphanum_fraction": 0.6137985726}
const fs = require('fs')
const path = require('path')
const sharp = require('sharp')
const Promise = require('promise')

class ImageOptimizer {
  constructor(originalImagePath) {
    this.originalImagePath = originalImagePath
    let originalExtension = path.extname(originalImagePath)
    this.imageName = path.basename(originalImagePath, originalExtension)
    this.images = {}
  }

  static outputDir() {
    return fs.realpathSync(`${__dirname}/../dist/images`)
  }

  process() {
    const buffer = fs.readFileSync(this.originalImagePath)
    return Promise.all([ Promise.resolve(this._convert(buffer, 1024, 'large')),
                         Promise.resolve(this._convert(buffer, 256, 'small')) ])
  }

  _convert(buffer, width, suffix) {
    const outputImage = `${this.imageName}-${suffix}.jpg`
    const self = this

    return new Promise(function (resolve, reject) {
      sharp(buffer)
        .resize(width)
        .withMetadata()
        .embed()
        .toFile(`${ImageOptimizer.outputDir()}/${outputImage}`, (err, result) => {
          if (err) {
            reject(err)
          }
          else {
            self.images[suffix] = outputImage
            resolve(self)
          }
        })
    })
  }
}

module.exports = ImageOptimizer
