import 'dart:async';
import 'package:dart_framework/utils/system_util.dart';
import 'package:oto/oto/application.dart';
import 'package:oto/oto/commands/command.dart';
import 'package:oto/oto/data/command_data.dart';

class BuildDart extends Command {
  Function? get error => null;

  Future<StringBuffer> appendShell(
      StringBuffer shell, DataCommand command) async {
    return dataFutrue(shell);
  }

  @override
  Future execute(DataCommand command) async {
    var data = DataBuildDart.fromJson(getParam(command));

    var shell = StringBuffer(getCDPath(workspace));
    shell.write(' $and flutter clean');
    shell.write(' $and flutter pub upgrade --major-versions');
    shell.write(' $and flutter packages upgrade');
    shell.write(' $and flutter pub get');
    if (data.executeBuildRunner == null ? true : data.executeBuildRunner!) {
      shell.write(
          ' $and flutter pub run build_runner build --delete-conflicting-outputs');
    }
    var script = await appendShell(shell, command);
    print(script);
    var process = await runtime.start(script,
        printStderr: false, logHandler: Application.logWithType);

    return await completeProcess(process, command);
  }
}

void registerBuildDartCommands() {
  Command.register(
    CommandType.BuildDart,
    () => BuildDart(),
    spec: const CommandSpec(
      type: CommandType.BuildDart,
      category: 'build',
      dataModel: 'DataBuildDart',
      samplePath: 'assets/yaml/sample/12_scheduler.yaml',
    ),
  );
}
