  import 'dart:convert';

// Web
import 'package:web/web.dart' as web;
import 'dart:js_interop';

import 'dart:typed_data';
import 'package:archive/archive.dart';
import 'package:xml/xml.dart';
import 'package:docx/docx.dart';

/// Recreate a Archive to add modification and save it on [fileInDocx]
/// [documentsXml] is list -> ['word/document.xml', 'word/_rels/document.xml.rels']
/// [docxEditor] Instance of docxEditor for Bytes, path,...
void save(List<XmlDocument> documentsXml, DocxEditor docxEditor) {
  try {
    final archive = ZipDecoder().decodeBytes(docxEditor.binaryInDocx!);

    final Uint8List uListDocumentXml = utf8.encode(documentsXml[0].toXmlString());
    final Uint8List uListDocumentXmlRels = utf8.encode(documentsXml[1].toXmlString());

    final newArchive = Archive();

    for (ArchiveFile file in archive.files) {
      if (file.name == 'word/document.xml') {
        newArchive.addFile(ArchiveFile(
          'word/document.xml',
          uListDocumentXml.length,
          uListDocumentXml,
        ));
      }
      else if (file.name == 'word/_rels/document.xml.rels') {
        newArchive.addFile(ArchiveFile(
          'word/_rels/document.xml.rels',
          uListDocumentXmlRels.length,
          uListDocumentXmlRels,
        ));
      } else {
        newArchive.addFile(file);
      }
    }
    for (ReplaceContent replaceCnt in docxEditor.replaceMap.values.where((rm) => rm.img != null)) {
      final imageBytes = replaceCnt.img!.bytes;
      newArchive.addFile(
        ArchiveFile(
          'word/media/${replaceCnt.img!.name}',
          imageBytes.length,
          imageBytes,
        )
      );
    }

    Uint8List zipData = ZipEncoder().encodeBytes(newArchive);

    String url = web.URL.createObjectURL(
      web.Blob(
        <JSUint8Array>[zipData.toJS].toJS,
        web.BlobPropertyBag(type: 'application/octet-stream'),
      ),
    );
    web.Document htmlDocument = web.document;
    web.HTMLAnchorElement anchor = htmlDocument.createElement('a') as web.HTMLAnchorElement;
    anchor.href = url;
    anchor.style.display = '${docxEditor.name ?? 'template'}.docx';
    anchor.download = '${docxEditor.name ?? 'template'}.docx';
    web.document.body!.add(anchor);
    anchor.click();
    anchor.remove();
    
  } catch (e) {
    throw StateError('DOCX BUILDER ERROR: $e');
  }
}
