import 'package:dart_framework/platform/process.dart';
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';

//git stash push
class GitStashPush extends Command {
  @override
  Future execute(DataCommand command) async {
    var data = DataGitStashPush.fromJson(getParam(command));

    var shell = StringBuffer(getCDPath(workspace));
    var includeUntracked = data.includeUntracked == null
        ? " -u"
        : (data.includeUntracked! ? " -u" : "");
    var message = data.message == null ? "" : " -m '${data.message}'";
    shell.write(' $and git stash push$includeUntracked$message');
    var process = await runtime.run(shell);
    if (data.setSuccess != null) {
      setProperty(
          data.setSuccess!, process.stdout.toString().contains('Saved'));
    }
    return await complete(process.exitCode, command);
  }
}

//git stash apply
class GitStashApply extends Command {
  @override
  Future execute(DataCommand command) async {
    var data = DataGitStashApply.fromJson(getParam(command));

    ProcessData process;
    var shell = StringBuffer(getCDPath(workspace));
    var apply =
        data.delete == null ? " pop" : (data.delete! ? " pop" : " apply");
    if (data.message == null) {
      shell.write(' $and git stash$apply');
      process = await runtime.start(shell, printStderr: false);
    } else {
      shell.write(' $and git stash list');
      var result = await runtime.run(shell);
      var exist = false;
      Application.log(result.stdout);
      shell = StringBuffer(getCDPath(workspace));
      if (result.exitCode == 0) {
        var arr = result.stdout.toString().split('\n');
        for (var line in arr) {
          var lineArr = line.split(': On ');
          if (lineArr.length > 1) {
            var id = lineArr[0];
            var content = lineArr[1];
            if (content.contains(data.message!)) {
              shell.write(' $and git stash$apply $id');
              exist = true;
              break;
            }
          }
        }
      }

      if (exist) {
        process = await runtime.start(shell, printStderr: false);
      } else {
        return await complete(0, command);
      }
    }
    return await completeProcess(process, command, passExitCodes: [1]);
  }
}
