import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:dart_framework/platform/platform_base.dart';
import 'package:yaml/yaml.dart';

enum Environment {
  local,
  dev,
  qa,
  product
}

int intMax = 0;
int intMin = 0;
bool isDebug = true;
String userPath = '';
String dataPath = '';
String scriptPath = '';
String executablePath = '';
String appIdendifier = '';
String appName = '';
String and = '&&';
Environment environment = Environment.local;

void initialize(String name, String appID) {
  initializeApp(name, appID);

  const env = String.fromEnvironment('ENV', defaultValue: 'local');
  environment = Environment.values.firstWhere(
    (e) => e.name == env, 
    orElse: () => Environment.local,
  );
}

Map<String, List<String>?> envArguments(List<String> arguments) {
  var dic = <String, List<String>?>{};
  var list = <String>[];
  var length = arguments.length;
  for (var i = 0; i < length; ++i) {
    var value = arguments[i];
    var key = _getKey(value);
    if (key != null) {
      var index = i + 1;
      list.clear();
      while (index < length) {
        var arg = arguments[index];
        if (_getKey(arg) == null) {
          list.add(arg);
          index++;
        } else {
          i = index - 1;
          break;
        }
      }
      List<String>? arr = List<String>.from(list);
      if (arr.isEmpty) arr = null;
      dic[key] = arr;
    }
  }
  return dic;
}

String? _getKey(String value) {
  String? key;
  if (value.indexOf('-') == 0) {
    key = value.substring(1, value.length);
  }
  return key;
}

Map<String, dynamic>? getMapFromJson(String jsonStr) {
  Map<String, dynamic>? map;
  if (jsonStr.length > 5) {
    JsonCodec codec = JsonCodec();
    try {
      map = codec.decode(jsonStr);
    } on Exception catch (e, stacktace) {
      print('Error: $e\n\n$stacktace');
    }
  }
  return map;
}

Map<String, dynamic>? getMapFromYaml(String yamlStr) {
  Map<String, dynamic>? map;
  if (yamlStr.length > 5) {
    try {
      map = jsonDecode(jsonEncode(loadYaml(yamlStr)));
    } on Exception catch (e, stacktace) {
      throw Exception('Yaml Pasing error.\n\n$stacktace');
    }
  }
  return map;
}

Future<String> getIPAddress(String domain) => getIPAddressPlatform(domain);

Future get simpleFuture {
  var c = Completer();
  c.complete();
  return c.future;
}

Future<T> dataFutrue<T>(T data) {
  var c = Completer<T>();
  c.complete(data);
  return c.future;
}

Future<Uint8List?> readFileByte(String filePath) => readFileBytePlatform(filePath);