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

import 'package:oto/oto/application.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 PublishiOS extends Command {
  Function? get error => null;

  @override
  Future execute(DataCommand command) async {
    var data = DataPublishiOS.fromJson(getParam(command));
    var menifestURL = data.menifestURL;
    var destinationPath = data.destinationPath;

    var templatePath = path.normalize(
        '${path.dirname(Platform.script.toFilePath())}/../assets/template');
    var indexContent = await File('$templatePath/index.html').readAsString();
    indexContent = indexContent
        .replaceAll('MENIFEST_URL', menifestURL)
        .replaceAll('APP_NAME', data.appName)
        .replaceAll('APP_VERSION', data.version)
        .replaceAll('APP_ICON_URL', data.displayImageURL);

    var destinationDir = Directory(destinationPath);
    if (!destinationDir.existsSync()) {
      await destinationDir.create(recursive: true);
    }
    var indexFile = File('$destinationPath/index.html');
    await indexFile.writeAsString(indexContent);

    Application.log('Created "index.html" --> "$destinationPath/index.html"');

    var menifestContent =
        await File('$templatePath/manifest.plist').readAsString();
    menifestContent = menifestContent
        .replaceFirst('IPA_URL', data.ipaURL)
        .replaceFirst('BUNDLE_ID', data.bundleID)
        .replaceFirst('VERSION', data.version)
        .replaceFirst('APP_NAME', data.appName)
        .replaceFirst('DISPLAY_IMAGE_URL', data.displayImageURL)
        .replaceFirst('FULL_SIZE_IMAGE_URL', data.fullSizeImageURL);
    var menifestFile = File('$destinationPath/manifest.plist');
    await menifestFile.writeAsString(menifestContent);

    Application.log('Created "manifest.plist" --> "$destinationPath/manifest.plist"');

    return complete(0, command);
  }
}

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