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

import 'package:cinema/feature/poster/poster.service.dart';
import 'package:cinema/feature/version/version.dart';
import 'package:cinema/feature/websocket/websocket.service.dart';
import 'package:cinema/injectable.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';

void main(List<String> args) async {
  final startTime = DateTime.now();

  configureDependencies();

  final router = Router();
  router.mount("/poster", getIt<PosterService>().router.call);

  // Configure a pipeline that logs requests.
  final handler = Pipeline().addMiddleware(logRequests()).addHandler(router.call);

  FutureOr<Response> combinedHandler(Request request) {
    if (request.url.path == 'ws') {
      return getIt<WebSocketService>().handler(request);
    }
    return handler(request);
  }

  // Use any available host or container IP (usually `0.0.0.0`).
  final ip = InternetAddress.anyIPv4;

  // For running in containers, we respect the PORT environment variable.
  final port = int.parse(Platform.environment['PORT'] ?? '3000');
  await io.serve(combinedHandler, ip, port, poweredByHeader: null).then((server) async {
    final bannerFile = File('banner.txt');
    if (await bannerFile.exists()) {
      final banner = await bannerFile.readAsString();
      print(banner);
    }

    getIt<Version>().printVersion();

    print('Serving at ${server.address.host}:${server.port}\n');

    final time = DateTime.now().difference(startTime);
    print('Server started at: $startTime');
    print('Startup time: $time\n');
  });
}
