'use strict'
const requestsync = require('sync-request'),
    user = process.argv[2] || 'user',
    pass = process.argv[3] || 'pass',
    site = process.argv[4] || 'https://social.hatthieves.es',
    url = site.split('://')[0] + '://' + user + ':' + pass + '@' + site.split('://')[1]

try {
    let actors,
        followed = [],
        count = 100,
        account = JSON.parse(requestsync('GET', url + '/api/v1/accounts/' + user).getBody()).id
    do {
        let id = actors && actors.length > 0 ? actors[actors.length - 1].id : '',
            body = requestsync('GET', url + '/api/v1/accounts/' + account + '/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)
    actors = []
    do {
        let id = actors && actors.length > 0 ? actors[actors.length - 1].id : '',
            body = requestsync('GET', url + '/api/statuses/networkpublic_timeline?max_id=' + id + '&only_media=false&count=20&with_muted=true')
        try {
            actors = JSON.parse(body.getBody())
            if (actors && actors.length > 0) {
                for (let a of actors) {
                    if (a && a.user && a.user.id && !followed.some(f => f === a.user.id)) {
                        requestsync('POST', url + '/api/v1/accounts/' + a.user.id + '/follow')
                        if (a.in_reply_to_user_id && !followed.some(f => f === a.in_reply_to_user_id)) {
                            requestsync('POST', url + '/api/v1/accounts/' + a.in_reply_to_user_id + '/follow')
                            followed.push(a.in_reply_to_user_id)
                            console.log('Following: ' + a.in_reply_to_user_id)
                        }
                        followed.push(a.user.id)
                        console.log('Following: ' + a.user.screen_name)
                    }
                }
            }
        } catch (e) {
            console.log(e)
        }
        console.log('Following: ' + followed.length + ' accounts')
    } while (actors && actors.length >= 20)
} catch (e) {
   console.log(e)
}
