import 'package:ambito/src/entity/_general/file/file_part.dart';
import 'package:ambito/src/entity/base_entity.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:isar/isar.dart';
import 'package:json_annotation/json_annotation.dart';

import '../_general/file/thumbnail.dart';
import '../_general/file/thumbnails.dart';

part 'list_measure.g.dart';

@collection
@JsonSerializable()
class ListMeasure extends BaseEntity {
  ListMeasure();

  @JsonKey(includeToJson: false, includeFromJson: false)
  @Id()
  late int isarId;
  @Index()
  int? id;

  @Index()
  String? name;
  String? description;

  List<String>? measureCategories;
  List<String>? measureGroups;
  List<String>? measureTypes;
  List<FilePart>? files;

  factory ListMeasure.fromJson(Map<String, dynamic> json) =>
      _$ListMeasureFromJson(json);

  Map<String, dynamic> toJson() => _$ListMeasureToJson(this);
}

extension ListMeasureExtension on ListMeasure {
  Widget? getImage() {
    Widget? image;
    if (files != null && files!.isNotEmpty) {
      if (files![0].thumbnails?.cardCover?.url != null) {
        image = CachedNetworkImage(
          width: 600,
          height: 350,
          imageUrl: files![0].thumbnails!.cardCover!.url!,
          placeholder: (context, url) => const CircularProgressIndicator(),
          errorWidget: (context, url, error) => const Icon(Icons.error),
          fit: BoxFit.cover,
        );
      }
    } else {
      return Image.asset(
        'assets/images/logo_trans.png',
        width: 300,
        height: 158,
        fit: BoxFit.fitHeight,
      );
    }
    return image;
  }

  CachedNetworkImage? getFullImage() {
    CachedNetworkImage? image;
    if (files != null && files!.isNotEmpty) {
      if (files![0].url != null) {
        image = CachedNetworkImage(
          imageUrl: files![0].url!,
          placeholder: (context, url) => const CircularProgressIndicator(),
          errorWidget: (context, url, error) => const Icon(Icons.error),
          fit: BoxFit.cover,
        );
      }
    }
    return image;
  }
}
