import 'dart:async';

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

class ArchiveiOS extends Command {
  Function? get error => null;

  @override
  Future execute(DataCommand command) async {
    var data = DataArchiveiOS.fromJson(getParam(command));
    var xcodeProjectPath =
        data.xcworkspaceFilePath ?? data.xcodeProjectFilePath;
    if (xcodeProjectPath == null) {
      throw Exception(
          '"xcodeProjectFilePath" or "xcworkspaceFilePath" must set at least one.');
    }
    var projectPath = Command.getPathNormal(xcodeProjectPath);
    var archivePath = Command.getPathNormal(data.archivePath);
    var destination = data.destination ?? "'generic/platform=iOS'";

    var project = '';
    if (data.xcworkspaceFilePath != null) {
      project = '-workspace $projectPath';
    } else {
      project = '-project $projectPath';
    }

    var shell = StringBuffer();
    shell.write(
        'xcodebuild $project -scheme ${data.scheme} -destination $destination -archivePath $archivePath archive');

    var process = await runtime.start(shell,
        workspace: workspace,
        printStderr: false,
        logHandler: Application.logWithType);

    return await completeProcess(process, command);
  }
}

class ExportiOS extends Command {
  Function? get error => null;

  @override
  Future execute(DataCommand command) async {
    var data = DataExportiOS.fromJson(getParam(command));
    var archivePath = Command.getPathNormal(data.archivePath);
    var exportPath = Command.getPathNormal(data.exportPath);
    var exportOptionPlistPath =
        Command.getPathNormal(data.exportOptionPlistPath);

    var shell = StringBuffer();
    shell.write(
        'xcodebuild -exportArchive -archivePath $archivePath -exportPath $exportPath -exportOptionsPlist $exportOptionPlistPath');

    var process = await runtime.start(shell,
        workspace: workspace,
        printStderr: false,
        logHandler: Application.logWithType);

    return await completeProcess(process, command);
  }
}
