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

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

class Delete extends Command {
  @override
  Future execute(DataCommand command) async {
    var data = DataDelete.fromJson(getParam(command));
    try {
      var ignoredList = data.ignorePattern ??= [];
      for (var item in data.list) {
        var path = Command.getPathNormal(item);
        var name = Path.getName(path);
        if (name == "*") {
          //Delete & recreate dest folder
          var dir = Directory(Path.getParent(path)!);
          if(dir.existsSync())
          {
            await dir.delete(recursive: true);
          }
        } else {
          var deletable = true;
          for(var ignoreItem in ignoredList)
          {
            if(name.contains(ignoreItem)) {
              deletable = false;
            }
          }

          if(deletable) {
            var file = File(path);
            if(file.existsSync()) {
              await file.delete(recursive: true);
              Application.log('Deleted File: ${file.path}');
            }
            var dir = Directory(path);
            if(dir.existsSync()) {
              await dir.delete(recursive: true);
              Application.log('Deleted Directory: ${dir.path}');
            }
          }
        }
      }

      if (ignoredList.isNotEmpty) {
        Application.log('==================== Ignored list ====================');
        for (var element in ignoredList) {
          Application.log(element);
        }
        Application.log('======================================================');
      }
    } on Exception {
      rethrow;
    }
    return complete(0, command);
  }
}

void registerDeleteCommand() {
  Command.register(
    CommandType.Delete,
    () => Delete(),
    spec: const CommandSpec(
      type: CommandType.Delete,
      category: 'file',
      dataModel: 'DataDelete',
      samplePath: 'assets/yaml/sample/07_file.yaml',
    ),
  );
}
