import { make_sync_no_matter_the_cost, render_and_copy } from "./common.tsx";
import { DOMParser } from "https://deno.land/x/deno_dom@v0.1.38/deno-dom-wasm.ts";

const try_so_so_hard_to_get_favicon_link = async (
    url: URL
): Promise<URL | undefined> => {
    const text = await (await fetch(url)).text();

    const doc = new DOMParser().parseFromString(text, "text/html");
    if (!doc) return;
    let link = doc.querySelector('link[rel="icon"]');
    if (!link) link = doc.querySelector('link[id="favicon"]');
    if (!link) link = doc.querySelector('link[rel="shortcut icon"]');
    if (!link) return;
    const href = link.getAttribute("href");
    if (!href) return;
    return new URL(href, url);
};

const Bookmark = async ({ url }: { url: string }) => {
    const u = new URL(url);

    const link = await try_so_so_hard_to_get_favicon_link(u);
    // if (!link) throw `figure it out: ${url}`;
    const l = link?.toString() || `https://${u.hostname}/favicon.ico`;

    return (
        <a href={url}>
            <img alt={`the favicon for ${u.hostname}`} src={l} style={{}} />
        </a>
    );
};

const urls = `
https://en.wikipedia.org/wiki/Main_Page
https://git.pyrope.net/
https://old.reddit.com/
https://stackexchange.com/
https://youtube.com/
https://jstris.jezevec10.com/u/mehbark
https://www.amazon.com/
https://mail.google.com/mail/u/0/#inbox
https://www.timeanddate.com/worldclock/turkey/istanbul
https://en.wikibooks.org/wiki/Main_Page
https://caltrop.dev/plop/
https://www.nytimes.com/games/wordle/index.html
https://rust-lang.github.io/rust-clippy/master/
https://cheats.rs/
https://www.rust-lang.org/
https://play.rust-lang.org/
https://pl.pyrope.net/main/friends
https://adventofcode.com/
https://godbolt.org/
https://www.codewars.com/dashboard
https://text.caltrop.dev/@-361,56
https://lichess.org/
https://translate.google.com/?sl=auto&tl=en&op=translate&hl=en
https://www.tumblr.com/blog/mehbark/activity
https://cohost.org/
https://feedly.com/i/collection/content/user/0b9f211d-d58b-4bc8-bcc7-3af7d33799a1/category/global.all
https://minesweeper.online/
`
    .trim()
    .split("\n");

const imgs = await Promise.all(urls.map(async url => await Bookmark({ url })));

render_and_copy(<>{...imgs}</>);
