import {Injectable} from '@angular/core';
import {MastodonApiAccountsService} from "../../../../../mastodon-api/src/lib/services/mastodon-api-accounts.service";
import {PersistentStore} from "../state/persistent/persistent-store.service";
import {EMPTY, expand, map, Observable, reduce} from "rxjs";
import {Account} from "../../../../../mastodon-api/src/lib/interfaces/public/account";

@Injectable({
    providedIn: 'root'
})
export class AccountService {

    constructor(private mastodonApiAccountsService: MastodonApiAccountsService,
                private store: PersistentStore) {

    }

    loadFollowings(): Observable<ReadonlyArray<Account>> {
        const applicationState = this.store.value;
        const instanceName = applicationState.currentInstance?.instanceName;
        const accessToken = applicationState.currentInstance?.accessToken;
        const accountId = applicationState.currentInstance?.accountId;
        return this.mastodonApiAccountsService
            .getFollowingsForAccount(instanceName, accessToken!, accountId)
            .pipe(
                expand(result => {
                    const nextLink = result[0];
                    if (nextLink && nextLink.length > 0) {
                        return this.mastodonApiAccountsService.getFollowingsForAccount(instanceName, accessToken!, accountId, nextLink);
                    }
                    return EMPTY;
                }),
                map(result => result[1]),
                reduce((acc: Account[], res: Account[]) => {
                    return acc.concat(res);
                }, []),
                map(accounts => accounts.sort((a, b) => a.username.localeCompare(b.username)) as ReadonlyArray<Account>),
            );
    }

}
