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/itg_forms_models/itg_forms_attachments_model.dart';
import 'package:mohem_flutter_app/widgets/dialogs/confirm_dialog.dart';
import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class ITGAttachmentsFragment extends StatelessWidget {
  List<ITGFormsAttachmentsModel> itgFormAttachmentsList;

  ITGAttachmentsFragment(this.itgFormAttachmentsList);

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemCount: itgFormAttachmentsList.length,
      itemBuilder: (context, index) {
        return Row(
          children: [
            SvgPicture.asset(determineFileIcon(itgFormAttachmentsList[index].fileType ?? "")),
            12.width,
            (itgFormAttachmentsList[index].fileName ?? "").toText16().expanded,
          ],
        ).objectContainerView().onPress(() async {
          try {
            String path = await _createFileFromString(itgFormAttachmentsList[index].fileBase64 ?? "", itgFormAttachmentsList[index].fileType ?? "");
            OpenFilex.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;
  }
}
