#!/usr/bin/env node
const path = require('path')
const fs = require('fs')
const updateNotifier = require('update-notifier')
const { Command } = require('commander')
const pkg = require('./package.json')
const {
  recurse,
  generateTiles,
  sanitiseName,
  restitchZoomTiles,
  convert
} = require('./functions.js')

// make sure we know where we are 🗺️
const workingDir = path.resolve(process.cwd()) // current path
const cliDir = path.dirname(process.argv[1]) // path library is running from

// check if there is an update 🕵️
const updateCheckInterval = 1000 * 60 * 60
updateNotifier({ pkg: { ...pkg }, updateCheckInterval }).notify()

const program = new Command()

program.version(pkg.version).description('Tiling Tool') // setup version

program
  .command('tile [input] [output] [format]')
  .description('Performing tile processing.')
  .action((input, output = 'dz_tilesets', format = 'deepzoom', cmd) => {
    const destExists = fs.existsSync(output)
    if (!destExists) fs.mkdirSync(output) // create output folder if it doesn't exist

    const inPath = path.resolve(workingDir, input)
    const outPath = path.resolve(workingDir, output)
    const isDir = fs.lstatSync(inPath).isDirectory()

    if (!isDir) {
      // if file
      generateTiles(inPath, outPath, format)
    } else {
      // if folder of files
      fs.readdirSync(inPath).map(file => {
        const filePath = path.resolve(inPath, file)
        const { ext } = path.parse(filePath)
        if (!['.jpg', '.tiff', '.png', '.jpeg'].includes(ext.toLowerCase()))
          return
        generateTiles(filePath, outPath, format)
      })
    }
    console.log('Please wait while processing finishes ... ️')
  })

// program
//   .command('restitch [input] [output]')
//   .description('Attempt to restitch zoomify tiles.')
//   .action((input, output = 'restitched', cmd) => {

//     const destExists = fs.existsSync(output);
//     if (!destExists) fs.mkdirSync(output); // create output folder if it doesn't exist

//     const inPath = path.resolve(workingDir, input);
//     const outPath = path.resolve(workingDir, output);

//     restitchZoomTiles(inPath, outPath);
//     console.log('Please wait while processing finishes ... ️');
//   });

program
  .command('convert [input] [format]')
  .description(
    `sanitise file names to lower-case with no spaces, it's good to run this on source files prior to tiling`
  )
  .action((input, format, cmd) => {
    convert(workingDir, input, format)
  })

program
  .command('sanitise [input]')
  .description(
    `sanitise file names to lower-case with no spaces, it's good to run this on source files prior to tiling`
  )
  .action((input, cmd) => {
    const inPath = path.resolve(workingDir, input)

    const options = {
      src: inPath,
      destination: inPath,
      mkdir: true,
      checkExists: false,
      process: ({ srcPath, destPath, destination, file }) => {
        const original = path.parse(srcPath).base
        const f = sanitiseName(srcPath)
        console.log(`       '${original}' renamed to '${path.parse(f).base}'`)
      }
    }

    recurse(options)
  })

program.parse(process.argv)
