'use strict'
const requestsync = require('sync-request'),
    fs = require('fs')

/*let body = requestsync('GET', 'https://social.hatthieves.es/api/v1/instance/peers'),
    urls = JSON.parse(body.getBody())*/

//for (let url of urls) {
let url = 'social.hatthieves.es',
    count = 100
//    try {
        let actors,
            followed = [],
            body
        do {
            let id = actors && actors.length > 0 ? actors[actors.length - 1].id : ''
            body = requestsync('GET', 'https://ale:pleroma.@' + url + '/api/v1/accounts/9lM7CeFGQNLWp38fgW/following?max_id=' + id + '&limit=' + count)
            try {
                actors = JSON.parse(body.getBody())
                if (actors && actors.length > 0) {
                    for (let a of actors) {
                        if (a && a.id && !followed.some(f => f === a.id)) {
                            followed.push(a.id)
                        }
                    }
                }
            } catch (e) {
                console.log(e)
            }
            console.log('Loading users: ' + followed.length)
        } while (actors && actors.length >= count && body.statusCode === 200)
        actors = []
        fs.readFileSync(__dirname + '/users.txt').toString('utf8').split('\n').map(u => {
            body = requestsync('GET', 'https://ale:pleroma.@' + url + '/api/v2/search?q=' + u + '&resolve=true')
            try {
                actors = JSON.parse(body.getBody())
                if (actors && actors.accounts && actors.accounts.length > 0) {
                    for (let a of actors.accounts) {
                        if (a && a.id && !followed.some(f => f === a.id)) {
                            requestsync('POST', 'https://ale:pleroma.@social.hatthieves.es/api/v1/accounts/' + a.id + '/follow')
                            followed.push(a.id)
                            console.log('following: ' + a.acct)
                        }
                    }
                }
            } catch (e) {
                console.log(e)
            }
            console.log(url + ' following: ' + followed.length)
        })
/*    } catch (e) {
        console.log(e)
    }*/
//}

