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

import 'package:oto/cli/commands/command_base.dart';
import 'package:dart_framework/utils/system_util.dart';
import 'package:oto/cli/commands/scheduler/scheduler_manager.dart';

class CommandScheduler extends CommandBase {
  @override
  Map<String, List<String>> get arguments => {
        '-l': ["Shows the currently operational schedulers."],
        '-r {file}': ["Register the defined file (yaml) with the scheduler."],
        '-u {alias}': [
          "Unregister schedules registered with the scheduler based on alias."
        ],
        '-e {alias} {bool}': ["Enables/disables the registered scheduler."]
      };
  @override
  String get name => 'scheduler';
  final SchedulerManager _scheduler;
  final void Function(int) _exitHandler;

  CommandScheduler({
    SchedulerManager? scheduler,
    void Function(int)? exitHandler,
  })  : _scheduler = scheduler ?? SchedulerManager.create(),
        _exitHandler = exitHandler ?? exit;

  @override
  Future execute(List<String> parameters) async {
    for (var i = 0; i < parameters.length; ++i) {
      var item = parameters[i];
      if (item.startsWith('-l')) {
        await _scheduler.showList();
        break;
      } else if (item.startsWith('-r')) {
        if (parameters.length > i + 1) {
          var file = parameters[i + 1];
          await _scheduler.regist(file);
        } else {
          printHelp();
        }
        _exitHandler(0);
        break;
      } else if (item.startsWith('-u')) {
        if (parameters.length > i + 1) {
          var alias = parameters[i + 1];
          await _scheduler.unregist(alias);
        } else {
          printHelp();
        }
        break;
      } else if (item.startsWith('-e')) {
        if (parameters.length > i + 2) {
          var alias = parameters[i + 1];
          // ignore: sdk_version_since
          var enable = bool.tryParse(parameters[i + 2]);
          if (enable == null) {
            printHelp();
          } else {
            await _scheduler.enableScheduler(alias, enable);
          }
        } else {
          printHelp();
        }
        break;
      }

      //================== for Debug ==================//
      else if (item.startsWith('-s')) {
        //hidden: start process
        await _scheduler.start();
        break;
      } else if (item.startsWith('-t')) {
        //hidden: terminate process
        await _scheduler.terminate();
        break;
      } else {
        printHelp();
      }
    }
    return simpleFuture;
  }

  @override
  String getDescription() {
    return ':::: Run as a service on the background.';
  }
}
