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

import 'package:dart_framework/utils/os_startup.dart';
import 'package:dart_framework/utils/system_util.dart';
import 'package:oto/cli/cli.dart';
import 'package:oto/cli/commands/command_base.dart';
import 'package:oto/cli/commands/command_const.dart';
import 'package:oto/cli/commands/install/regist_path.dart';
// import 'package:oto/resources.resource_importer.dart';

class CommandInstall extends CommandBase {
  @override
  String get name => 'install';

  @override
  Future execute(List<String> parameters) async {
    var label = CLI.serviceName;
    if (!await OSStartup.isRegistedStartup(label)) {
      var installPath = CommandConstant.OS!.installPath;
      //Create install folder
      var installDir = Directory(installPath);
      if (!installDir.existsSync()) {
        await installDir.create(recursive: true);
      }

      if (Platform.isWindows) {
        await installFiles(installPath);
      }

      //Copy executable file
      var target = File(Platform.resolvedExecutable);
      var installFilePath = CommandConstant.OS?.installFilePath;
      await target.copy(installFilePath!);

      //Regist path
      await RegistPath.OS?.add(installPath);

      //Create startup
      await OSStartup.registStartup(installFilePath, label,
          arguments: ['start']);
      printOut('Successfully installed.', PrintType.information);
    } else {
      printOut('Installation failed because it was already installed',
          PrintType.error);
    }
    return simpleFuture;
  }

  Future installFiles(String installPath) async {
    await File('$installPath/silentbatch.exe').create();
    // await file.writeAsBytes(silentbatch);
    return simpleFuture;
  }

  @override
  String getDescription() {
    return ':::: Install for the startup program to run on the background.';
  }
}

class CommandUninstall extends CommandBase {
  @override
  String get name => 'uninstall';

  @override
  Future execute(List<String> parameters) async {
    var c = Completer<bool>();
    var label = CLI.serviceName;
    if (await OSStartup.isRegistedStartup(label)) {
      var installPath = CommandConstant.OS!.installPath;
      //To-do: Proccess kill

      //Regist path
      await RegistPath.OS?.remove(installPath);

      //Remove Installed file
      var installDir = Directory(installPath);
      if (installDir.existsSync()) {
        await installDir.delete(recursive: true);
      }

      //Remove startup
      await OSStartup.unregistStartup(label);
      printOut('Successfully removed.', PrintType.information);
    } else {
      printOut("It's already been uninstalled.", PrintType.warning);
    }
    return c.future;
  }

  @override
  String getDescription() {
    // ignore: prefer_interpolation_to_compose_strings
    return ':::: Delete from the startup program and remove the file.';
  }
}