######################################################################
# Pia Portal - Pia's standard discovery protocol.
# -----
# Licensed under Apache 2.0
module PortalProtocol
using ..Pia
using ExtraFun

const REGISTRY_STORE_VERSION = 0x1

struct PortalListing{S}
    address::Address{S}
    endpoint::Optional{Endpoint}
    last_seen::Float64
    scores::Dict{Symbol, Float32}
end
PortalListing(address::Address{S}) where S = PortalListing{S}(address, nothing, 0, Dict())


export PiaPortal
mutable struct PiaPortal{S} <: DiscoveryProtocol
    basedir::String
    lock::ReentrantLock
    
    function PiaPortal{S}(basedir, lock) where S
        @assert S isa Integer
        UInt32(S) # Ensures S is a *value* which can be re/stored
        new{S}(basedir, lock)
    end
end
PiaPortal(S::Integer, basedir::AbstractString = "./.Pia.portal") = PiaPortal{S}(basedir, ReentrantLock())


function resolve(portal::PiaPortal, transport::TransportProtocol, addr::Address)::Endpoint
    try
        return getpeer(portal, addr).endpoint::Endpoint
    catch; end
    
    error("not implemented")
end

function Pia.connect(transport::TransportProtocol, portal::PiaPortal, app::AbstractApplication)
    # TODO: Attempt to connect to rated peers
    
    return Pia.connect(transport, app)
end

end # module PortalProtocol
