// ignore_for_file: depend_on_referenced_packages

import 'dart:async';
import 'dart:io';

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

class Rename extends Command {
  @override
  Future execute(DataCommand command) async {
    var data = DataRename.fromJson(getParam(command));
    var entries = data.renameMap.entries;
    try {
      for (var entry in entries) {
        var start = Command.getPathNormal(entry.key);
        var targetName = entry.value;
        var type = Path.getType(start);
        var parentPath = Path.getParent(start)!;
        var newPath = path.join(parentPath, targetName);
        if (type == FileType.directory) {
          await Directory(start).rename(newPath);
        } else {
          await File(start).rename(newPath);
        }

        Application.log('Rename: $start --> ${path.basename(newPath)}');
      }
    } on Exception catch (e) {
      Application.log('Copy General Exception: $e');
    }
    return complete(0, command);
  }
}

void registerRenameCommand() {
  Command.register(
    CommandType.Rename,
    () => Rename(),
    spec: const CommandSpec(
      type: CommandType.Rename,
      category: 'file',
      dataModel: 'DataRename',
      samplePath: 'assets/yaml/sample/07_file_utils.yaml',
    ),
  );
}
