import '../webextension-polyfill';
import { RpcServer } from 'webextension-rpc';
import { h, render } from 'preact';
import classes from './index.module.scss';
import { App } from './App';
import { discoverAnnotationsEmbeddedAsJSONLD } from './discovery';
import { annotateSelection } from './AnnotationCreationHelper';

export const contentScriptRpcServer = new RpcServer({
  annotateSelection,
  discoverAnnotationsEmbeddedAsJSONLD: async () =>
    discoverAnnotationsEmbeddedAsJSONLD(),
  // fetchJson: async (...args: Parameters<typeof fetch>) => {
  //   const response = await fetch(...args);
  //   let json;
  //   try {
  //     json = await response.json();
  //   } catch (error) {
  //     json = undefined;
  //   }
  //   const { ok, redirected, status, statusText, type, url } = response;
  //   return {
  //     json,
  //     headers: response.headers.entries(),
  //     ok,
  //     redirected,
  //     status,
  //     statusText,
  //     type,
  //     url,
  //   };
  // },
});

main();
async function main() {
  const containerId = classes.container;
  let container = document.getElementById(containerId);
  if (!container) {
    container = document.createElement('div');
    // use class as id too.
    container.id = containerId;
    container.setAttribute('class', classes.container);
    document.body.append(container);
  }
  render(<App appContainer={container} />, container);
}
