import {Injectable, OnDestroy} from '@angular/core';
import {EMPTY, expand, map, Observable, reduce, Subscription} from "rxjs";
import {select, Store} from "@ngrx/store";
import {Account, MastodonApiAccountsService} from 'projects/mastodon-api/src/public-api';
import {selectDataForAuthorizedRequest} from "../state/store";

@Injectable({
    providedIn: 'root'
})
export class AccountService implements OnDestroy {
    private instanceName: string | undefined;
    private accessToken: string | undefined;
    private accountId: string | undefined;
    private storeSubscription: Subscription;

    constructor(private mastodonApiAccountsService: MastodonApiAccountsService, private store: Store) {
        this.storeSubscription = this.store.pipe(select(selectDataForAuthorizedRequest)).subscribe(data => {
            this.instanceName = data?.instanceName;
            this.accessToken = data?.accessToken;
            this.accountId = data?.accountId;
        });
    }

    ngOnDestroy(): void {
        this.storeSubscription.unsubscribe();
    }

    loadFollowings(): Observable<ReadonlyArray<Account>> {
        return this.mastodonApiAccountsService
            .getFollowingsForAccount(this.instanceName!, this.accessToken!, this.accountId!)
            .pipe(
                expand(result => {
                    const nextLink = result[0];
                    if (nextLink && nextLink.length > 0) {
                        return this.mastodonApiAccountsService
                            .getFollowingsForAccount(this.instanceName!, this.accessToken!, this.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>),
            );
    }

}
