import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/models/get_attachement_list_model.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';

class AttachmentsFragment extends StatelessWidget {
  final List<GetAttachementList> getAttachmentList;

  AttachmentsFragment(this.getAttachmentList);

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemCount: getAttachmentList.length,
      itemBuilder: (context, index) {

        return Row(
          children: [
            SvgPicture.asset(determineFileIcon(getAttachmentList[index].fILECONTENTTYPE ?? "")),
            12.width,
            (getAttachmentList[index].fILENAME ?? "").toText16().expanded,
          ],
        ).objectContainerView().onPress(() async {
          try {
            String path = await _createFileFromString(getAttachmentList[index].fILEDATA ?? "", getAttachmentList[index].fILECONTENTTYPE ?? "");
            OpenFile.open(path);
          } catch (ex) {Utils.showToast("Cannot open file.");
          }
        });
      },
      separatorBuilder: (BuildContext context, int index) => 12.height,
    ).paddingAll(21);
  }

  String determineFileIcon(String fileContentType) {
    String icon = "";
    switch (fileContentType) {
      case "pdf":
        icon = "assets/images/pdf.svg";
        break;
      case "xls":
        icon = "assets/images/xls.svg";
        break;
      case "xlsx":
        icon = "assets/images/xls.svg";
        break;
      case "png":
        icon = "assets/images/png.svg";
        break;
      case "jpg":
        icon = "assets/images/jpg.svg";
        break;
      case "jpeg":
        icon = "assets/images/jpg.svg";
        break;
    }
    return icon;
  }

  Future<String> _createFileFromString(String encodedStr, String ext) async {
    Uint8List bytes = base64.decode(encodedStr);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + "." + ext);
    await file.writeAsBytes(bytes);
    return file.path;
  }
}
