import 'dart:async';
import 'dart:io';
import 'package:dart_framework/utils/system_util.dart';
import 'package:oto/oto/commands/build/build_dart.dart';
import 'package:oto/oto/commands/command.dart';
import 'package:oto/oto/data/command_data.dart';
// ignore: depend_on_referenced_packages
import 'package:path/path.dart' as path;

class BuildDartCompile extends BuildDart {
  @override
  Future<StringBuffer> appendShell(
      StringBuffer shell, DataCommand command) async {
    var c = Completer<StringBuffer>();
    var data = DataBuildDartCompile.fromJson(getParam(command));
    var extension = getExeExtension();
    var binPath = path.join(workspace, 'bin');

    //find build target
    var targetDir = Directory(binPath);
    var findedDartFile = '';
    var fileList = targetDir.listSync();
    for (var file in fileList) {
      findedDartFile = path.basename(file.path);
      break;
    }
    findedDartFile = path.join(workspace, 'bin', findedDartFile);
    var targetDartFile = data.targetDartFile ?? findedDartFile;

    //clear build path
    var buildFolderName = 'release';
    var buildPath = path.join(workspace, buildFolderName);
    var buildDir = Directory(buildPath);
    var buildFileName = data.buildFileName ?? 'release';
    if (!buildDir.existsSync()) {
      buildDir.createSync();
    }
    buildPath =
        path.join(workspace, buildFolderName, '$buildFileName$extension');
    var preBuildFile = File(buildPath);
    if (preBuildFile.existsSync()) {
      preBuildFile.deleteSync();
    }

    shell.write(' $and dart compile exe "$targetDartFile" -o "$buildPath"');
    c.complete(shell);
    return c.future;
  }

  String getExeExtension() {
    if (Platform.isWindows) {
      return '.exe';
    } else {
      return '';
    }
  }
}

void registerBuildDartCompileCommands() {
  Command.register(
    CommandType.BuildDartCompile,
    () => BuildDartCompile(),
    spec: const CommandSpec(
      type: CommandType.BuildDartCompile,
      category: 'build',
      dataModel: 'DataBuildDartCompile',
    ),
  );
}
