import 'dart:html' as html;
import 'dart:ui_web' as ui_web;

import 'package:flutter/material.dart';

typedef ImageLoadingBuilder = Widget Function();
typedef ImageErrorBuilder = Widget Function(Object error);

final Set<String> _registeredViewTypes = <String>{};

Widget buildPlatformNetworkImage({
  required Uri uri,
  required BoxFit fit,
  required double? width,
  required double? height,
  required ImageLoadingBuilder loadingBuilder,
  required ImageErrorBuilder errorBuilder,
}) {
  final url = uri.toString();
  final viewType = 'destination-image-${url.hashCode}';

  if (_registeredViewTypes.add(viewType)) {
    ui_web.platformViewRegistry.registerViewFactory(viewType, (int viewId) {
      return html.ImageElement()
        ..src = url
        ..draggable = false
        ..style.width = '100%'
        ..style.height = '100%'
        ..style.border = '0'
        ..style.display = 'block'
        ..style.pointerEvents = 'none'
        ..style.objectFit = _cssObjectFit(fit);
    });
  }

  return SizedBox(
    width: width,
    height: height,
    child: HtmlElementView(viewType: viewType),
  );
}

String _cssObjectFit(BoxFit fit) {
  switch (fit) {
    case BoxFit.contain:
      return 'contain';
    case BoxFit.fill:
      return 'fill';
    case BoxFit.fitHeight:
    case BoxFit.fitWidth:
    case BoxFit.scaleDown:
      return 'contain';
    case BoxFit.none:
      return 'none';
    case BoxFit.cover:
      return 'cover';
  }
}
