import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';

import '../services/auth_service.dart';

class LoginAwareCachedNetworkImage extends StatelessWidget {
  static final _logger = Logger('$LoginAwareCachedNetworkImage');
  final String imageUrl;
  final double? width;
  final double? height;

  const LoginAwareCachedNetworkImage({
    super.key,
    required this.imageUrl,
    this.width,
    this.height,
  });

  @override
  Widget build(BuildContext context) {
    final profile = context.watch<AccountsService>().currentProfile;

    Map<String, String>? headers;

    try {
      final imageServer = Uri.parse(imageUrl).host;
      if (imageServer == profile.serverName) {
        headers = {'Authorization': profile.credentials.authHeaderValue};
      }
    } catch (e) {
      _logger.severe('Error Parsing ImageURL: $e');
    }

    return CachedNetworkImage(
      httpHeaders: headers,
      imageUrl: imageUrl,
      width: width,
      height: height,
    );
  }
}
