import 'dart:typed_data';

import 'package:chat/photo/engine/lru_cache.dart';
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';

class FirstPhotoItem extends StatefulWidget {
  final AssetPathEntity pathEntity;
  final double size;
  final Function onSelectFolder;

  const FirstPhotoItem(
      {Key key, this.pathEntity, this.size = 50, this.onSelectFolder})
      : super(key: key);

  @override
  _FirstPhotoItemState createState() => _FirstPhotoItemState();
}

class _FirstPhotoItemState extends State<FirstPhotoItem> {
  AssetEntity entity;

  @override
  void initState() {
    super.initState();
    getAssetEntity();
  }

  Widget _buildImg(Uint8List data) {
    return ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Image.memory(
          data,
          width: widget.size,
          height: widget.size,
          fit: BoxFit.contain,
        ));
  }

  Future getAssetEntity() async {
    var entityList = await widget.pathEntity.getAssetListPaged(0, 1);
    setState(() {
      entity = entityList.first;
    });
  }

  @override
  Widget build(BuildContext context) {
    Widget leading;

    if (entity == null) {
      leading = Container(
          width: widget.size,
          height: widget.size,
          child: CircularProgressIndicator(),
          padding: EdgeInsets.all(8));
    } else {
      var thumb = ImageLruCache.getData(entity);
      if (thumb != null) {
        leading = _buildImg(thumb);
      } else {
        leading = FutureBuilder<Uint8List>(
            future: entity.thumbDataWithSize(
                widget.size.toInt(), widget.size.toInt()),
            builder: (BuildContext context, AsyncSnapshot<Uint8List> snapshot) {
              var futureData = snapshot.data;
              if (snapshot.connectionState == ConnectionState.done &&
                  futureData != null) {
                ImageLruCache.setData(entity, widget.size.toInt(), futureData);
                return _buildImg(futureData);
              } else {
                return Center(
                  child: Container(
                    width: 30.0,
                    height: 30.0,
                    child: CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation(Colors.blueAccent),
                    ),
                  ),
                );
              }
            });
      }
    }

    return ListTile(
        leading: leading,
        title: Text(widget.pathEntity.name),
        subtitle: Text('${widget.pathEntity.assetCount}'),
        onTap:widget.onSelectFolder);
  }
}
