'use strict';

// This tests snapshot JS API using the example in the docs.

require('../common');
const assert = require('assert');
const { spawnSync } = require('child_process');
const tmpdir = require('../common/tmpdir');
const fixtures = require('../common/fixtures');
const path = require('path');
const fs = require('fs');

const v8 = require('v8');

// By default it should be false. We'll test that it's true in snapshot
// building mode in the fixture.
assert(!v8.startupSnapshot.isBuildingSnapshot());

tmpdir.refresh();
const blobPath = path.join(tmpdir.path, 'snapshot.blob');
const entry = fixtures.path('snapshot', 'v8-startup-snapshot-api.js');
{
  for (const book of [
    'book1.en_US.txt',
    'book1.es_ES.txt',
    'book2.zh_CN.txt',
  ]) {
    const content = `This is ${book}`;
    fs.writeFileSync(path.join(tmpdir.path, book), content, 'utf8');
  }
  fs.copyFileSync(entry, path.join(tmpdir.path, 'entry.js'));
  const child = spawnSync(process.execPath, [
    '--snapshot-blob',
    blobPath,
    '--build-snapshot',
    'entry.js',
  ], {
    cwd: tmpdir.path
  });
  if (child.status !== 0) {
    console.log(child.stderr.toString());
    console.log(child.stdout.toString());
    assert.strictEqual(child.status, 0);
  }
  const stats = fs.statSync(path.join(tmpdir.path, 'snapshot.blob'));
  assert(stats.isFile());
}

{
  const child = spawnSync(process.execPath, [
    '--snapshot-blob',
    blobPath,
    'book1',
  ], {
    cwd: tmpdir.path,
    env: {
      ...process.env,
      BOOK_LANG: 'en_US',
    }
  });

  const stdout = child.stdout.toString().trim();
  const stderr = child.stderr.toString().trim();
  assert.strictEqual(stderr, 'Reading book1.en_US.txt');
  assert.strictEqual(stdout, 'This is book1.en_US.txt');
  assert.strictEqual(child.status, 0);
}
