#!/usr/local/bin/node

const fs = require('fs-extra')
const meow = require('meow')
const path = require('path')
const spawn = require('projector-spawn')
const promisify = require('util').promisify
const Faced = require('faced')
const faced = new Faced()

const cli = meow(
  `
  Usage: $ tomify <input>

  Options:
    --output, -o Output Path
    --debug, -d Debug

  Examples:
    $ tomify file1.jpg file2.jpg -o ./new-folder
`,
  {
    alias: { h: 'help', o: 'output', d: debug },
    defaults: { debug: false }
  }
)

/**
 * CLI
 */

if (cli.input.length === 0 && !cli.flags.input) {
  console.error('Specify at least one path')
  process.exit(1)
}

let dest = cli.flags.output || process.cwd()
fs.ensureDirSync(dest)
console.error('Destination: %s', dest)

/**
 * Build Toms
 */
const toms = []
for (let file of cli.input) {
  toms.push(
    new Promise((resolve, reject) =>
      findFace(file, dest).then(addTom).then(resolve).catch(reject)
    )
  )
}

Promise.all(toms)
  .then(() => console.log('Done!'))
  .catch(err => {
    if (err.stderr) console.error(err.stderr)
    else console.error(err)
    process.exit(err.code || 1)
  })

function findFace(file, dest) {
  return new Promise((resolve, reject) => {
    debug('Processing %s...', file)
    faced.detect(file, (faces, image, file) => {
      if (faces.length === 0) {
        reject(new Error(`Faces not found in ${file}`))
        return
      }

      debug('Face face in %s...', file)
      const face = faces[0]
      const height = parseInt(face.getHeight() * 1.75)
      const width = parseInt(face.getWidth() * 1.75)
      const top = parseInt(face.getX() - (height * .25))
      const left = parseInt(face.getY() - (width * .25))
      resolve([dest, file, top, left, height, width])
    })
  })
}

function addTom([dest, file, top, left, height, width]) {
  let meta = path.parse(file)
  dest = path.join(dest, `${meta.name}.gif`)
  console.error('Tomifying %s...', meta.base)
  return spawn(
    'convert',
    [
      file,
      'null:',
      '\(',
      path.join(__dirname, 'tom.gif'),
      '-resize',
      `${height}`,
      '\)',
      '-geometry',
      `+${top}+${left}`,
      '-layers',
      'composite',
      '-delete',
      0,
      '-loop',
      0,
      dest
    ],
    {
      cwd: process.cwd()
    }
  )
}

function debug(msg) {
  if (cli.flags.debug) console.error(msg)
}

@@ -337,16 +337,53 @@
 ut Path%0A
+    --resize, -r Resize Number, 1.25%0A
     --de
@@ -509,45 +509,28 @@
  d: 
+'
 debug
- %7D,%0A    defaults: %7B debug: false
+', r: 'resize'
  %7D%0A 
@@ -665,16 +665,172 @@
 xit(1)%0A%7D
+%0Aif (!cli.flags.resize) cli.flags.resize = 1%0Aelse if (typeof cli.flags.resize !== 'number') %7B%0A  console.error('resize must be a number')%0A  process.exit(1)%0A%7D
 %0A%0Alet de
@@ -953,16 +953,17 @@
 oms%0A */%0A
+%0A
 const to
@@ -1315,16 +1315,43 @@
 )%0A  %7D)%0A%0A
+/**%0A * Find all Faces%0A */%0A%0A
 function
@@ -1699,25 +1699,93 @@
 nst 
-height = parseInt
+centerX = (face.getX() + (face.getWidth() / 2))%0A      const centerY = (face.getY() + 
 (fac
@@ -1798,22 +1798,20 @@
 eight() 
-* 1.75
+/ 2)
 )%0A      
@@ -1820,24 +1820,38 @@
 nst 
-w
+tomW
 idth = 
-parseInt
+cli.flags.resize * 
 (fac
@@ -1889,20 +1889,37 @@
 t to
-p = parseInt
+mHeight = cli.flags.resize * 
 (fac
@@ -1927,28 +1927,23 @@
 .get
-X() - (h
+H
 eight
+()
  * 
-.25)
+1.75
 )%0A  
@@ -1956,51 +1956,77 @@
 nst 
-left = parseInt(face.getY() - (width * .25)
+x = centerX - (tomWidth / 2)%0A      const y = centerY - (tomHeight / 2
 )%0A  
@@ -2050,36 +2050,37 @@
 , file, 
-top, left, h
+x, y, tomH
 eight, 
-w
+tomW
 idth%5D)%0A 
@@ -2089,24 +2089,53 @@
  %7D)%0A  %7D)%0A%7D%0A%0A
+/**%0A * Add Tom to Image%0A */%0A%0A
 function add
@@ -2656,16 +2656,34 @@
 %0A  )%0A%7D%0A%0A
+/**%0A * Debug%0A */%0A%0A
 function

improve comments, proper centering of tom.gif