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

// Returns the total commit count
class GitCount extends Command {
  @override
  Future execute(DataCommand command) async {
    var data = DataGitCount.fromJson(getParam(command));

    var shell = StringBuffer(getCDPath(workspace));
    shell.write(' $and git rev-list --all HEAD --all --count');
    var process = await runtime.start(shell, printStderr: false);
    var number = int.parse(process.stdoutArr.last);
    await setProperty(data.setValue, number);

    return await completeProcess(process, command);
  }
}

// Returns the git revision hash
class GitRev extends Command {
  @override
  Future execute(DataCommand command) async {
    var data = DataGitRev.fromJson(getParam(command));

    var shell = StringBuffer(getCDPath(workspace));
    var target = data.branch ?? 'HEAD';
    shell.write(' $and git fetch origin');
    shell.write(' $and git rev-parse $target');
    var process = await runtime.start(shell, printStderr: false);
    var hash = process.stdoutArr.last;
    await setProperty(data.setValue, hash);

    return await completeProcess(process, command);
  }
}

// Resets git working tree to a clean state
class GitReset extends Command {
  @override
  Future execute(DataCommand command) async {
    var data = DataGitReset.fromJson(getParam(command));

    var shell = StringBuffer(getCDPath(workspace));
    var force = data.force! ? 'f' : '';
    shell.write(' $and git reset --hard');
    shell.write(' $and git clean -${force}d');
    var process = await runtime.start(shell, printStderr: false);

    return await completeProcess(process, command);
  }
}
