import 'dart:convert';
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';

// Ignorable errors are suppressed
class GitBranch extends Command {
  @override
  Future execute(DataCommand command) async {
    var data = DataGitBranch.fromJson(getParam(command));

    var shell = StringBuffer('cd ${data.path}');
    shell.write(
        ' $and git for-each-ref --format=\'{"ref": "%(refname:short)", "sha": "%(objectname)", "date": "%(committerdate:iso8601)"}\' refs/remotes | jq -s . > branches.json');

    var process = await runtime.start(shell);

    var file = File('${data.path}/branches.json');
    var content = file.readAsStringSync();
    final List<dynamic> decoded = jsonDecode(content);
    final branches = decoded.map((e) => BranchInfo.fromJson(e)).toList();
    var features = <String>[];
    var releases = <String>[];
    var fixedBranch = ['main', 'master', 'develop'];
    var existBranch = [];
    var excludeBranch = ['origin'];
    var startDate = DateTime.now().subtract(Duration(days: data.startDay!));
    for (var branch in branches) {
      var branchName = branch.ref!.replaceFirst('origin/', '');
      if (!excludeBranch.contains(branchName)) {
        if (fixedBranch.contains(branchName)) {
          existBranch.add(branchName);
        } else if (DateTime.parse(branch.date!)
                .toUtc()
                .difference(startDate)
                .inSeconds >
            0) {
          if (branchName.startsWith('release')) {
            releases.add(branchName);
          } else {
            features.add(branchName);
          }
        }
      }
    }
    existBranch.sort();
    existBranch.addAll(releases);
    existBranch.addAll(features);
    setProperty(data.setBranches!, existBranch, showPrint: true);

    return await completeProcess(process, command);
  }
}
