import Favicon from "react-favicon";
import { WSState } from "./MatrixWS";

// Taken from https://github.com/element-hq/element-web/blob/0577e245dac944bd85eea07b93a9762a93062f62/src/favicon.ts
function getInitialFavicon(): HTMLLinkElement[] {
  const icons: HTMLLinkElement[] = [];
  const links = window.document
    .getElementsByTagName("head")[0]
    .getElementsByTagName("link");
  for (const link of links) {
    if (
      link.hasAttribute("rel") &&
      /(^|\s)icon(\s|$)/i.test(link.getAttribute("rel")!)
    ) {
      icons.push(link);
    }
  }
  return icons;
}

const iconPath = getInitialFavicon()[0].getAttribute("href")!;

export function AppIconModifier(p: {
  numberUnread: number;
  state: string;
}): React.ReactElement {
  const isError = p.state === WSState.Error || p.state === WSState.Closed;
  return (
    <Favicon
      url={iconPath}
      alertFillColor={isError ? "orange" : undefined}
      alertCount={isError ? "x" : p.numberUnread}
    />
  );
}
