// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:io' as io;

import 'package:build_bucket_golden_scraper/build_bucket_golden_scraper.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';

void main() {
  test('parses command-line arguments', () {
    // Create a fake engine directory.
    final io.Directory buildRoot = io.Directory.systemTemp.createTempSync(
      'build_bucket_golden_scraper_test_engine',
    );
    final io.Directory srcDir = io.Directory(p.join(buildRoot.path, 'src'))..createSync();
    io.Directory(p.join(srcDir.path, 'flutter')).createSync();

    // Does not run, but just parses.
    try {
      final BuildBucketGoldenScraper scraper = BuildBucketGoldenScraper.fromCommandLine(<String>[
        '--dry-run',
        '--engine-src-path',
        srcDir.path,
        'https://ci.chromium.org/raw/buildbucket/v1/builders/flutter/flutter-linux/builder:linux_bare',
      ]);

      expect(scraper.dryRun, isTrue);
      expect(scraper.engine.srcDir.path, srcDir.path);
      expect(
        scraper.pathOrUrl,
        'https://ci.chromium.org/raw/buildbucket/v1/builders/flutter/flutter-linux/builder:linux_bare',
      );
    } finally {
      buildRoot.deleteSync(recursive: true);
    }
  });

  test('finds diffs', () async {
    // Create a fake engine directory.
    final io.Directory buildRoot = io.Directory.systemTemp.createTempSync(
      'build_bucket_golden_scraper_test_engine',
    );
    final io.Directory srcDir = io.Directory(p.join(buildRoot.path, 'src'))..createSync();
    io.Directory(p.join(srcDir.path, 'flutter', 'docs')).createSync(recursive: true);

    // Create an empty logo in docs/flutter_logo.png.
    final io.File logo = io.File(p.join(srcDir.path, 'flutter', 'docs', 'flutter_logo.png'))
      ..createSync();

    // Create a fake log file.
    try {
      final io.File logFile = io.File(p.join(buildRoot.path, 'log.txt'))..createSync();
      logFile.writeAsStringSync('''
See also the base64 encoded /b/s/w/ir/cache/builder/src/flutter/docs/flutter_logo_new.png:
[encoded data, 5676 characters]
''');

      // Tell the runner to extract diffs.
      final StringBuffer outSink = StringBuffer();
      final BuildBucketGoldenScraper scraper = BuildBucketGoldenScraper(
        pathOrUrl: logFile.path,
        engineSrcPath: srcDir.path,
        outSink: outSink,
      );

      // Run.
      final int result = await scraper.run();
      expect(result, 0);

      // Check the output.
      expect(outSink.toString(), contains('Wrote 1 golden file changes:'));
      expect(outSink.toString(), contains('docs/flutter_logo.png'));
      expect(logo.readAsBytesSync().length, 4257);
    } finally {
      buildRoot.deleteSync(recursive: true);
    }
  });
}
