import axios from 'axios'
import path from 'path'
import fs from 'fs-extra'
import { spawn } from 'child_process'

export function startVikunja (bin, jwtSecret, workDir = false, deleteDb = false) {
  if (!workDir) {
    workDir = path.dirname(bin)
  }

  if (deleteDb) {
    // clear the database
    try {
      fs.unlinkSync(path.join(workDir, 'vikunja.db'))
    } catch (_) {
      // ignore error
    }
  }

  return new Promise(resolve => {
    const vikunja = spawn(
      bin,
      [],
      {
        cwd: workDir,
        env: {
          VIKUNJA_SERVICE_JWTSECRET: jwtSecret
        }
      }
    )
    vikunja.stdout.on('data', (data) => {
      data = data.toString()
      console.log(data)
      if (data.indexOf(' cmd/func25') !== -1) {
        console.log('Vikunja started, will proceed with data population...')
        setTimeout(() => resolve(), 1000)
      }
    })
  })
}

export async function initClient (baseURL, username, password, registerUser) {
  if (registerUser) {
    await axios.post(
      baseURL + '/api/v1/register',
      {
        username,
        password,
        email: 'demo@example.com'
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )
  }

  // login
  const bearer = (await axios.post(
    baseURL + '/api/v1/login',
    {
      username,
      password
    },
    {
      headers: {
        'Content-Type': 'application/json'
      }
    }
  )).data.token

// prepare client
  return axios.create({
    baseURL: baseURL + '/api/v1/',
    headers: { 'Authorization': 'Bearer ' + bearer }
  })
}
