import 'dart:io';

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

class XcodeprojAddFile extends Command {
  Function? get error => null;
  String rubyCode = '''
# add_file_xcodeproj.rb
# encoding: UTF-8
require 'xcodeproj'

project = Xcodeproj::Project.open('{XCODEPROJ_PATH}')
target = project.targets.find { |t| t.name == '{TARGET}' }
group = project.main_group
file_ref = group.new_file('{ADD_FILE_PATH}')

# Add file to target
build_file = target.add_file_references([file_ref]).first

# Explicitly add to Copy Bundle Resources
target.resources_build_phase.add_file_reference(file_ref)

project.save

puts "✅ {ADD_FILE_PATH} has been added to the project and included in Copy Bundle Resources."
''';

  /*
  * sudo gem install xcodeproj
  */

  @override
  Future execute(DataCommand command) async {
    var data = DataXcodeprojAddFile.fromJson(getParam(command));
    var template = rubyCode
        .replaceAll('{TARGET}', data.target)
        .replaceAll('{ADD_FILE_PATH}', data.addFilePath)
        .replaceAll('{XCODEPROJ_PATH}', data.xcodeprojPath);

    var file = File('${data.workspace}/add_file_xcodeproj.rb');
    file.writeAsStringSync(template, flush: true);

    var shell = StringBuffer();
    shell.write('export LANG=en_US.UTF-8 && cd ${data.workspace}');
    shell.write(' && ruby add_file_xcodeproj.rb');

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

    return await completeProcess(process, command);
  }
}

void registerXcodeprojCommands() {
  Command.register(
    CommandType.XcodeprojAddFile,
    () => XcodeprojAddFile(),
    spec: const CommandSpec(
      type: CommandType.XcodeprojAddFile,
      category: 'build',
      dataModel: 'DataXcodeprojAddFile',
      samplePath: 'assets/yaml/sample/10_build_tools.yaml',
    ),
  );
}
