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

import 'package:network_proxy/network/util/host_filter.dart';

import '../channel.dart';
import '../handler.dart';
import '../http/codec.dart';
import '../util/logger.dart';
import '../util/system_proxy.dart';

Future<void> main() async {
  ProxyServer().start();
}

class ProxyServer {
  bool init = false;
  int port = 8888;
  bool _enableSsl = false;

  EventListener? listener;
  Server? server;

  ProxyServer({this.listener});

  bool get enableSsl => _enableSsl;

  File configFile() {
    var userHome = Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];
    var separator = Platform.pathSeparator;
    return File("${userHome!}$separator.proxyPin${separator}config.cnf");
  }

  set enableSsl(bool enableSsl) {
    _enableSsl = enableSsl;
    server?.enableSsl = enableSsl;
    if (server == null || server?.isRunning == false) {
      return;
    }

    if (Platform.isMacOS) {
      SystemProxy.setSslProxyEnableMacOS(enableSsl, port);
    }
  }

  /// 启动代理服务
  Future<Server> start() async {
    Server server = Server();
    if (!init) {
      init = true;
      await _loadConfig();
    }
    server.enableSsl = _enableSsl;
    server.initChannel((channel) {
      channel.pipeline.handle(HttpRequestCodec(), HttpResponseCodec(), HttpChannelHandler(listener: listener));
    });
    return server.bind(port).then((serverSocket) {
      log.i("listen on $port");
      SystemProxy.setSystemProxy(port, enableSsl);
      this.server = server;
      return server;
    });
  }

  /// 停止代理服务
  Future<Server?> stop() async {
    log.i("stop on $port");
    if (Platform.isMacOS) {
      await SystemProxy.setProxyEnableMacOS(false, enableSsl);
    } else if (Platform.isWindows) {
      await SystemProxy.setProxyEnableWindows(false);
    }
    await server?.stop();
    return server;
  }

  void restart() {
    stop().then((value) => start());
  }

  Future<void> _loadConfig() async {
    var file = configFile();
    var exits = await file.exists();
    if (!exits) {
      return;
    }
    Map<String, dynamic> config = jsonDecode(await file.readAsString());
    log.i('加载配置文件 [$file] $config');
    enableSsl = config['enableSsl'] == true;
    port = config['port'] ?? port;
    HostFilter.whitelist.load(config['whitelist']);
    HostFilter.blacklist.load(config['blacklist']);
  }

  void flushConfig() async {
    var file = configFile();
    await file.create(recursive: true);
    HostFilter.whitelist.toJson();
    HostFilter.blacklist.toJson();
    var json = jsonEncode(toJson());
    log.i('刷新配置文件 $runtimeType ${toJson()}');
    file.writeAsString(json);
  }

  Map<String, dynamic> toJson() {
    return {
      'port': port,
      'enableSsl': enableSsl,
      'whitelist': HostFilter.whitelist.toJson(),
      'blacklist': HostFilter.blacklist.toJson(),
    };
  }
}
