import { expect } from "e2e";
import JSZip from "jszip";
import { test, WEB } from "./t3.ts";

async function docx(picture: boolean) {
  const drawing = `<w:p><w:r><w:drawing><wp:inline><wp:extent cx="1905000" cy="1143000"/><wp:docPr id="1" name="Bar chart"/><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic><pic:nvPicPr><pic:cNvPr id="1" name="Bar chart"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="rIdSvg"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1905000" cy="1143000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>`;
  const zip = new JSZip()
    .file('[Content_Types].xml', `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="svg" ContentType="image/svg+xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>`)
    .file('_rels/.rels', `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>`)
    .file('word/document.xml', `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><w:body><w:p><w:r><w:t>Quarterly report</w:t></w:r></w:p>${picture ? drawing : ''}<w:p><w:r><w:t>End of report</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr></w:body></w:document>`);
  if (picture) {
    zip.file('word/_rels/document.xml.rels', `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdSvg" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.svg"/></Relationships>`);
    zip.file('word/media/image1.svg', `<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120" viewBox="0 0 200 120"><rect width="200" height="120" fill="#f1f5f9"/><path d="M20 10V100H190" fill="none" stroke="#334155" stroke-width="2"/><rect x="40" y="60" width="30" height="40" fill="#2563eb"/><rect x="90" y="35" width="30" height="65" fill="#16a34a"/><rect x="140" y="15" width="30" height="85" fill="#f59e0b"/></svg>`);
  }
  return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' });
}

test('Word previews a directly referenced embedded SVG picture', WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project('Document preview', {'svg-picture.docx': await docx(true), 'no-picture.docx': await docx(false)});
  const thread = await t3.thread({project, title:'Review Word document', messages:['Start']});
  await browser.setViewport({width:1440,height:1080});
  await t3.open(thread);
  await screen.getByRole('button', 'Toggle right panel').tap();
  await screen.getByRole('button', 'Files F').tap();
  await screen.getByRole('button', 'Maximize panel').tap();
  await screen.getByRole('treeitem', 'no-picture.docx').tap();
  await screen.getByText('1 page', {exact:false}).waitFor({timeout:120_000});
  await screen.getByText('End of report', {exact:true}).waitFor();
  await app.screenshot('no-picture-control');
  await screen.getByRole('treeitem', 'svg-picture.docx').tap();
  try {
    await expect(screen.getByText('1 page', {exact:false})).toBeVisible({timeout:120_000});
    await expect(screen.getByText('Quarterly report', {exact:true})).toBeVisible();
    await expect(screen.getByText('End of report', {exact:true})).toBeVisible();
    await expect.poll(() => browser.evaluate(() => {
      const source = document.querySelector('canvas');
      if (!source || !source.width) return 0;
      const copy = document.createElement('canvas');
      copy.width = source.width; copy.height = source.height;
      const context = copy.getContext('2d')!;
      context.drawImage(source, 0, 0);
      const pixels = context.getImageData(0, 0, copy.width, copy.height).data;
      let colored = 0;
      for (let i=0; i<pixels.length; i+=4) {
        if ((pixels[i] < 70 && pixels[i+2] > 170) || (pixels[i] < 60 && pixels[i+1] > 100 && pixels[i+2] < 100) || (pixels[i] > 200 && pixels[i+1] > 100 && pixels[i+2] < 80)) colored++;
      }
      return colored;
    })).toBeGreaterThan(100);

  } finally {
    await app.screenshot('svg-picture');
  }
});
