from app.libraries.setup import Setup
from app.libraries.database import Database
from app.libraries.peers import Peers
from app.libraries.nodeinfo import Nodeinfo
import ray

ray.init(num_cpus = 25) # Specify this system CPUs.

@ray.remote
def peerapi(peer):

    api = peers.getapi(peer) # get peer nodeinfo's URL

    if api != '':

        db.write_server(peer, api)

        print(f'server: {peer}, api: {api}')

        server_peers.remote(peer)

    else:

        db.write_deadserver(peer)

        print(f'*** server: {peer}, api not found!')

@ray.remote
def server_peers(server):

    peers_list = peers.getpeers(server) # check and get peers if available

    if peers_list != None: # if peers list is available

        print(f'\n{server}: {len(peers_list)} peers\n')

        db.update_peer(server) #update peer

        for peer in peers_list:

            print(f'{server}({len(peers_list)}): checking peer {peer}...')

            found = db.check_peer(peer)

            if not found:

                peerapi.remote(peer)

if __name__ == '__main__':

    db = Database()

    setup = Setup()

    peers = Peers()

    peers_list = peers.getpeers(setup.mastodon_hostname) #get peers from Mastodon host

    if peers_list != None:

        ray.get([peerapi.remote(peer) for peer in peers_list])

