import { PeerInfo } from '../types/basicTypes'
import { paths } from './files'
import { parseCookie, post } from './networkUtils'
import utils from './utils'

export function peerToString(peer: {
    host: string
    port: string | number
}): string {
    return `${peer.host}:${peer.port}`
}

export function isPeerSameAs(peer1: PeerInfo, peer2: PeerInfo): boolean {
    return peer1.host === peer2.host && peer1.port === peer2.port
}

export function updatePeersFile(
    peers: PeerInfo[],
    updatedPeer: PeerInfo
): void {
    const updatedPeers = peers.map((x) => {
        if (isPeerSameAs(updatedPeer, x)) {
            return {
                ...x,
                ...updatedPeer,
            }
        } else {
            return x
        }
    })

    utils.WriteFile(JSON.stringify(updatedPeers, null, 2), paths.peersFile)
}

export async function loginToPeer(peer: PeerInfo): Promise<string | Error> {
    const { data, error, cookie } = await post<{
        result: string
        msg: string
    }>({
        hostname: peer.host,
        path: '/api/login',
        port: peer.port,
        bodyObject: { pw: peer.pw },
        http: peer.http,
    })

    if (error || !data || data.result !== 'success') {
        return data ? new Error(data.msg) : error
    }

    const parsedCookies = parseCookie(cookie)
    return parsedCookies.sessionID
}
