#!/usr/bin/env node
import { readFileSync, writeFile } from 'fs'

import { program } from 'commander'

import chordsong from './index'
import { join } from 'path'

const pkgJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf8'))

program.showHelpAfterError()

program.version(pkgJson.version, '-v, --version', 'output the current version')

program.showHelpAfterError()

program.arguments('<inputfile>')

program.option('-o, --output <outputfile>', 'set the output file name. If omitted the output filename is the input one with the extension switched to .html')

program.option('-r, --render-mode <mode>', 'select default render mode. Either \'chordName\' or \'diagram\'', 'chordName')

program.option('-t, --theme <theme>', 'force using a user-provided theme instead of the default one. Generate a directory at ./themes/<theme> with files 00-fonts.css, 01-theme.css, 02-diagram.css, and index.html. You may take themes/default dir as reference.', 'default')

program.parse(process.argv)

console.log(program.args)

const inputFile: string = program.args[0]

const options = program.opts()

let outputFile: string = options.output

if (outputFile === undefined) {
  const pos = inputFile.lastIndexOf('.')
  outputFile = inputFile.substr(0, pos < 0 ? inputFile.length : pos) + '.html'
}

if (options.renderMode !== 'diagram' && options.renderMode !== 'chordName') { program.help() }

const text = readFileSync(inputFile, 'utf8')

const renderedSong = chordsong(text, options.renderMode, options.theme) as string

writeFile(outputFile, renderedSong, 'utf8', (err: any) => {
  if (err != null) throw err
  console.log('Output saved to ' + outputFile)
})
