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

class Shell extends Command {
  @override
  Future execute(DataCommand command) async {
    var data = DataShell.fromJson(getParam(command));
    var shell = StringBuffer(getCDPath(workspace));
    var commands = data.commands;
    for (var item in commands) {
      shell.write(' $and $item');
    }

    var process = await runtime.start(shell);
    if (data.setMessage == null) {
      return await completeProcess(process, command);
    } else {
      await process.waitForExit();
      var str = process.stdout.toString();
      var length = str.length;
      str = str.substring(0, length - 1);
      await setProperty(data.setMessage!, str);
      return await complete(process.exitCode!, command);
    }
  }
}

class ShellFile extends Command {
  @override
  Future execute(DataCommand command) async {
    var data = DataShellFile.fromJson(getParam(command));
    var path = Command.getPathNormal(data.path);
    var shell = StringBuffer();
    if (Platform.isWindows) {
      shell.writeln('call $path');
    } else {
      shell.writeln('source $path');
    }
    var process = await runtime.start(shell);

    return await completeProcess(process, command);
  }

  bool isSuccess(int exitCode) {
    var success = false;
    if (exitCode == 0 || exitCode == 128) {
      success = true;
    }
    return success;
  }
}

void registerShellCommands() {
  Command.register(
    CommandType.Shell,
    () => Shell(),
    spec: const CommandSpec(
      type: CommandType.Shell,
      category: 'shell',
      dataModel: 'DataShell',
      samplePath: 'assets/yaml/sample/14_shell_process.yaml',
    ),
  );
  Command.register(
    CommandType.ShellFile,
    () => ShellFile(),
    spec: const CommandSpec(
      type: CommandType.ShellFile,
      category: 'shell',
      dataModel: 'DataShellFile',
      samplePath: 'assets/yaml/sample/14_shell_process.yaml',
    ),
  );
}
