import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'
import { startVikunja, initClient } from '../src/vikunja.js'
import personAsList from '../src/person-as-list.js'
import { keypress } from '../src/utils.js'

function addGlobal (yargs) {
  yargs
    .option('startVikunja', {
      alias: 's',
      description: 'Vikinja binary to be started before data are populated or Vikunja has to be started manually'
    })
    .option('workDir', {
      description: 'directory where Sqlite database will be created if startVikunja was provided, default is folder with Vikunja binary'
    })
    .option('deleteDb', {
      'description': 'WARNING! Database will be delete before Vikunja will be started'
    })
    .option('jwtsecret', {
      default: 'C519352B2E9FFBADD92AE5BC63D26A42FC334418373150F8137618EC1F7459D3'
    })
    .option('user', {
      alias: 'u',
      default: 'demo'
    })
    .option('password', {
      alias: 'P',
      default: 'demo'
    })
    .option('baseUrl', {
      default: 'http://localhost:3456'
    })

  return yargs
}

async function startVikunjaFromArgv (argv) {
  if (argv.startVikunja) {
    return startVikunja(argv.startVikunja, argv.jwtsecret, argv.workDir, argv.deleteDb).then(() => true)
  }

  return false
}

function initClientFromArgv (wasStarted, argv) {
  return initClient(argv.baseUrl, argv.user, argv.password, wasStarted)
}

yargs(hideBin(process.argv))
  .command(
    '$0 person-as-list',
    'will populate Vikunja tasks with persons as lists',
    yargs => {
      addGlobal(yargs)
        .option('count', {
          alias: 'c',
          default: 100
        })
    },
    async argv => {
      const wasStarted = await startVikunjaFromArgv(argv)
      await personAsList(await initClientFromArgv(wasStarted, argv), argv.count)

      if (wasStarted) {
        console.log('population done, press any key to quit')
        await keypress()
        process.exit()
      }
    }
  )
  .demandCommand(1)
  .help()
  .parse()

