import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:aitrainer_app/library/image_cache.dart' as wt;
import 'package:aitrainer_app/library/transparent_image.dart';

class MenuImage extends StatelessWidget {
  final int? workoutTreeId;
  final String imageName;
  double radius;
  MenuImage({
    required this.workoutTreeId,
    required this.imageName,
    this.radius = 24,
  });

  @override
  Widget build(BuildContext context) {
    if (workoutTreeId == null) {
      return Offstage();
    }
    String? imageString = this.getImage(workoutTreeId!, imageName);
    Widget? widget;
    if (imageString != null) {
      widget = ClipRRect(
          borderRadius: BorderRadius.circular(24.0),
          child: Container(
            color: Colors.transparent,
            child: FadeInImage(
              fadeInDuration: Duration(milliseconds: 100),
              image: MemoryImage(base64Decode(imageString)),
              placeholder: MemoryImage(kTransparentImage),
            ),
          ));
    } else {
      if (imageName.contains("https")) {
        if (!wt.ImageCache().existsImageInMap(workoutTreeId!, imageName)) {
          widget = ClipRRect(
              borderRadius: BorderRadius.circular(radius),
              child: Container(
                color: Colors.transparent,
                child: FadeInImage(
                  fadeInDuration: Duration(milliseconds: 500),
                  image: NetworkImage(imageName),
                  placeholder: MemoryImage(kTransparentImage),
                ),
              ));
        }
      } else {
        widget = ClipRRect(
            borderRadius: BorderRadius.circular(radius),
            child: Container(
              color: Colors.transparent,
              child: Image.asset(imageName),
            ));
      }
    }
    if (widget == null) {
      return Offstage();
    }
    return widget;
  }

  String? getImage(int id, String name) {
    String? imageString;
    if (name.contains("http")) {
      imageString = wt.ImageCache().getImageString(id, name);
    }
    return imageString;
  }
}
