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

import 'package:archive/archive.dart';
import 'package:flutter_test/flutter_test.dart';

import 'package:badnote/services/office/docx_parser.dart';
import 'package:badnote/services/office/pptx_parser.dart';

ArchiveFile _xml(String name, String body) {
  final bytes = Uint8List.fromList(body.codeUnits);
  return ArchiveFile(name, bytes.length, bytes);
}

void main() {
  test('PptxParser extracts slide text from minimal OOXML', () async {
    final archive = Archive();
    archive.addFile(_xml(
      '[Content_Types].xml',
      '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"></Types>',
    ));
    archive.addFile(_xml(
      'ppt/presentation.xml',
      '<?xml version="1.0"?><p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">'
      '<p:sldSz cx="12192000" cy="6858000"/></p:presentation>',
    ));
    archive.addFile(_xml(
      'ppt/slides/slide1.xml',
      '<?xml version="1.0"?><p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" '
      'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">'
      '<p:cSld><p:spTree><p:sp><p:txBody><a:p><a:r><a:t>Hello Slide</a:t></a:r></a:p></p:txBody></p:sp>'
      '</p:spTree></p:cSld></p:sld>',
    ));

    final encoded = ZipEncoder().encode(archive)!;
    final dir = await Directory.systemTemp.createTemp('pptx_test_');
    final path = '${dir.path}/t.pptx';
    await File(path).writeAsBytes(encoded);

    final parsed = await PptxParser().parse(path);
    expect(parsed.slides, isNotEmpty);
    expect(parsed.plainText, contains('Hello Slide'));
    await dir.delete(recursive: true);
  });

  test('DocxParser extracts paragraphs from minimal OOXML', () async {
    final archive = Archive();
    archive.addFile(_xml(
      '[Content_Types].xml',
      '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"></Types>',
    ));
    archive.addFile(_xml(
      'word/document.xml',
      '<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
      '<w:body><w:p><w:r><w:t>Linear Algebra</w:t></w:r></w:p></w:body></w:document>',
    ));
    final encoded = ZipEncoder().encode(archive)!;
    final dir = await Directory.systemTemp.createTemp('docx_test_');
    final path = '${dir.path}/t.docx';
    await File(path).writeAsBytes(encoded);

    final parsed = await DocxParser().parse(path);
    expect(parsed.plainText, contains('Linear Algebra'));
    await dir.delete(recursive: true);
  });
}
