import 'dart:io';
import 'dart:typed_data';

import 'package:dart_framework/platform/platform_base.dart';
import 'package:dart_framework/utils/system_util.dart';
import 'package:dart_framework/utils/path.dart';
import 'package:path/path.dart' as path;

import 'package:dart_framework/platform/isolate_manager.dart';
import 'package:dart_framework/utils/string_util.dart';
import 'package:dart_framework/data/isolate_data.dart';

// Interfaces
LogWriter getLogWriter() => LogWriterIO();

void initialize(String name, String appID) {
  appIdendifier = appID;
  appName = name;
  scriptPath = Platform.script.toFilePath(windows: Platform.isWindows);
  executablePath = Platform.executable;
  isDebug =
      path.basenameWithoutExtension(Platform.resolvedExecutable) == 'dart';
  var debugPath = isDebug ? '.debug' : '';
  userPath = Path.userPath;
  dataPath = '${Path.dataPath}$debugPath';
  and = Platform.isWindows ? ';' : '&&';

  intMax = 9007199254740991;
  intMin = -intMax;
}

Future<String> getIPAddress(String domain) async {
  late String ipAddress;
  var regEx = RegExp(r'(://)([a-zA-Z0-9-.]+)(/|:)');
  var match = regEx.firstMatch(domain);
  if (match != null && match.groupCount > 2) {
    domain = match.group(2)!;
    var list = await InternetAddress.lookup(domain);
    for (var address in list) {
      ipAddress = address.address;
      break;
    }
  }
  return dataFutrue(ipAddress);
}

Future<Uint8List?> readFileByte(String filePath) async {
  Uri myUri = Uri.parse(filePath);
  File audioFile = File.fromUri(myUri);
  Uint8List? bytes;
  await audioFile.readAsBytes().then((value) {
    bytes = Uint8List.fromList(value);
    print('reading of bytes is completed');
  }).catchError((onError) {
    print('Exception Error while reading audio from path:$onError');
  });
  return dataFutrue(bytes);
}



class LogWriterIO extends IsolateBase implements LogWriter {
  late int _id;
  late File _file;
  @override
  void onReady(Object? initData) async {
    if ((initData as String?) != null) {
      var dir = Directory(initData as String);
      if (dir.existsSync()) {
        _file = File(path.normalize(
            '${dir.path}/log_${getDates().replaceAll(' ', '_').replaceAll(':', '-')}.txt'));
        await _file.create();
        print('[LogWriterIO] onReady - path: ${_file.path}');
        send(IsoMessege('ready', data: _file.path));
        addEventListener('write', onWrite);
        requester();
      }
    }
  }

  void requester() async {
    while (true) {
      await Future.delayed(const Duration(seconds: 3));
      send(IsoMessege('request'));
    }
  }

  void onWrite(Object? message) {
    // print('write in file: $message');
    if(!_file.existsSync()) _file.createSync(recursive: true);
    _file.writeAsStringSync(message as String, mode: FileMode.append);
  }

  @override
  void start(
      String path, Map<String, void Function(Object?)> messageListenerMap) {
    var handler =
        IsolateManager.create<LogWriterIO>(LogWriterIO(), initData: path);
    handler.addEventListener(IsolateEvent.ready, (data) => _id = data as int);
    for (var element in messageListenerMap.entries) {
      handler.addListener(element.key, element.value);
    }
  }

  @override
  void write(String log) {
    IsolateManager.send(_id, IsoMessege('write', data: log));
  }

  @override
  void end() {
    IsolateManager.exit(_id);
  }
}