import 'dart:io';
import 'package:dart_framework/subtitle/parser_smi.dart';
import 'package:dart_framework/subtitle/parser_srt.dart';
import 'package:dart_framework/utils/os_startup.dart';
import 'package:dart_framework/utils/system_util.dart';
import 'package:dart_framework/core/application.dart';
import 'package:dart_framework/charset.dart';
import 'package:dart_framework/platform/isolate_manager.dart' as isolate;

import 'package:path/path.dart' as path;

void main() async {
  Application('dartframework', 'com.toki-labs.dartframework', () async {
    print(await OSStartup.unregistStartup(appIdendifier));

    isolate.test();

    // print(await OSStartup.isRegistedStartup(appIdendifier));

    // print(await OSStartup.registStartup(
    //     Platform.resolvedExecutable, appIdendifier,
    //     logStandardFilePath: '$dataPath\\startup_log.txt',
    //     logErrorFilePath: '$dataPath\\startup_err.txt'));

    // var md5 = generateMd5('test');
    // print('$md5 / ${md5.length}');
    // var encrypted = encrypt('test', 'this is test');
    // print(encrypted);

    // var raw = decrypt('test', encrypted);
    // print(raw);
  }, (error, stack) {
    print(error);
    print(stack);
    exit(0);
  });
}

void testParse() {
  var filePath = Platform.script.toFilePath(windows: true);
  var file = File('${path.dirname(path.dirname(filePath))}/test_utf16le.smi');
  var bytes = file.readAsBytesSync();
  var encoding = Charset.detect(bytes);
  print(encoding);
  var result = encoding!.decode(bytes);

  var ext = path.extension(file.path).toLowerCase();
  if (ext == '.smi') {
    //SMI
    var parser = ParserSMI();
    var subtitles = parser.getSubtitlesData(result);
    var index = 0;
    for (var item in subtitles.subtitles) {
      print('$index. ${item.text}');
      index++;
    }
  } else if (ext == '.srt') {
    //SRT
    var parser = ParserSRT();
    var subtitles = parser.getSubtitlesData(result);
    var index = 0;
    for (var item in subtitles.subtitles) {
      print('$index. ${item.text}');
      index++;
    }
  }
}


/*
@override
  Future<bool> isRegistedStartup(String label) async {
    var shell = 'Get-ScheduledTask | Where-Object {\$_.TaskName -eq "$label"}';
    var process = await Process.run('powershell.exe', [shell]);
    var exist = false;
    if (process.exitCode == 0) {
      var existLine = <String>[];
      var stdoutList = process.stdout.toString().split('\n');
      for (var item in stdoutList) {
        var result = item.trim();
        if (result.isNotEmpty) {
          existLine.add(item);
        }
      }
      if (existLine.length > 2) {
        exist = true;
      }
    }
    return dataFutrue(exist);
  }

  //shell file must have '#!/bin/sh'
  @override
  Future<bool> registStartup(String executableFilePath, String label,
      {List<String>? arguments,
      String? logStandardFilePath,
      String? logErrorFilePath}) async {
    var scriptPath = '${dataPath.replaceAll('/', '\\')}\\$label.ps1';
    var startupScript = startupScriptTemplate.replaceAll(
        '{EXECUTABLE_PATH}', executableFilePath.replaceAll('/', '\\'));
    var args = '';
    if (arguments != null) {
      args = '''-ArgumentList "${arguments.join(' ')}" `
              ''';
    }
    startupScript = startupScript.replaceAll('{ARGUMENTS}', args);
    var startupFile = File(scriptPath);
    startupFile.createSync(recursive: true);
    startupFile.writeAsStringSync(startupScript, flush: true);

    var schedulerScript = schedulerScriptTemplate
        .replaceAll('{SCRIPT_PATH}', scriptPath)
        .replaceAll('{TASK_NAME}', label);

    var logStdout = '';
    if (logStandardFilePath != null) {
      logStdout = ' > ${logStandardFilePath.replaceAll('/', '\\')}';
    }
    schedulerScript = schedulerScript.replaceAll('{LOG_STDOUT}', logStdout);

    var logStderr = '';
    if (logErrorFilePath != null) {
      logStderr = ' 2> ${logErrorFilePath.replaceAll('/', '\\')}';
    }
    schedulerScript = schedulerScript.replaceAll('{LOG_STDERR}', logStderr);

    var tempFile =
        File('${Directory.systemTemp.path}\\${ProcessExecutor.tempFileName}');
    tempFile.createSync(recursive: true);
    tempFile.writeAsStringSync(schedulerScript, flush: true);

    var powershellCommand =
        'Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command `& \'${tempFile.path}\'; exit" -Verb RunAs -WindowStyle Hidden';

    var process =
        await Process.run('powershell', ['-Command', powershellCommand]);

    print(process.stdout.toString());
    print(process.stderr.toString());
    print(process.exitCode);

    return dataFutrue(process.exitCode == 0);
  }

  @override
  Future<bool> unregistStartup(String label) async {
    var shell = 'Unregister-ScheduledTask -TaskName "$label" -Confirm:\$false';
    var process = await Process.run('powershell.exe', [shell]);
    print(process.stdout.toString());
    print(process.stderr.toString());
    print(process.exitCode);
    return dataFutrue(process.exitCode == 0);
  }
  */