import { NetworkComparisonHandler, ErrorConditionHandler, AsnHandler } from "./peering-handlers"
import { Network } from "./peering-models-net"
import { apple } from './peering-utils-constants'

async function handleRequest(request) {
    const url = new URL(request.url)
    const asn = url.searchParams.get('asn')
    console.log(`asn:${asn}`)
    try {
        if (asn) {
            const apNetwork = await new Network(apple['asn']).populate()
            const otherNetwork = await new Network(asn).populate()
            const sharedItems = await apNetwork.compare(otherNetwork)
            console.log(`sharedItems: ${sharedItems.length}`)
            let response = await fetch(request.url)
            return await new HTMLRewriter()
                .on('#asnField', new AsnHandler(asn))
                .on('#formContainer', new NetworkComparisonHandler({apNetwork, otherNetwork, sharedItems}))
                .transform(response)
        } else {
            return fetch(request.url)
        }
    } catch (e) {
        console.error(`error:${e}`)
        let response = await fetch(request.url)
        return await new HTMLRewriter()
            .on('#asnField', new AsnHandler(asn))
            .on('#formContainer', new ErrorConditionHandler(asn))
            .transform(response)
    }
}
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})