const childProcess = require('child_process')

export function update () {
  unzipWep2()
  migrateSchema()
}

/**
 * Create necessary directories and copying files from the WePublish Editor 2 npm package
 */
export async function unzipWep2 (projectName = null): Promise<void> {
  console.log('Unzipping WePublish Editor 2 files...')
  const options = {
    stdio:[0,1,2]
  }
  if (projectName) {
    options['cwd'] = `./${projectName}`
  }
  try {
    await childProcess
      .execSync(
        `mkdir -p schema && cp -R ./node_modules/@wep2/editor/schema/* ./schema/`,
        options
      )
  } catch (e) {
    console.log(e)
  }

  // TODO: unzip all extensions
  console.log('Todo: Unzip Directus extensions.')
}

/**
 * Migrate the Directus database with the schema of the WePublish Editor 2
 */
export async function migrateSchema (projectName: string = null): Promise<void> {
  console.log('Implement WePublish Editor 2 schema to Directus...')
  const options = {
    stdio:[0,1,2]
  }
  if (projectName) {
    options['cwd'] = `./${projectName}`
  }
  try {
    await childProcess
      .execSync(
        'npx directus schema apply ./schema/schema.yaml',
        options
      )
  } catch (error) {
    console.log(error)
  }
}
