import { execFile as execFileC } from 'child_process'
import { promisify } from 'util'
import config from './config.js'
import pty from 'node-pty'

const execFile = promisify(execFileC)

const exec = async (binary, args = []) => {
  return (await execFile(binary, args)).stdout
}

export async function containerExists (containerId) {
  return (await runningContainers()).some(c => c.Id === containerId)
}

export async function runningContainers () {
  return JSON.parse((await exec(config.containerBinary,
    ['ps', '--filter', `label=${config.containerLabel}`, '--format=json']
  )))
}

export function getContainerShell (containerId, shell = 'sh') {
  return pty.spawn(config.containerBinary, ['exec', '-it', containerId, shell], {
    name: 'xterm-color',
    cols: 30,
    rows: 40,
  })
}

export function startContainer (image = 'alpine', cmd = ['sh', '-c', 'while true; do sleep 1d; done']) {
  return exec(config.containerBinary, ['run', '--rm', '-d', '-l', config.containerLabel, image, ...cmd])
}

