import {Injectable} from "@angular/core";
import {MastodonApiService} from "./mastodon-api.service";
import {map, Observable} from "rxjs";
import {GetAccountResponse} from "../interfaces/responses/get_account_response";
import {Account} from "../interfaces/public/account";
import {HttpResponse} from "@angular/common/http";

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

    constructor(private mastodonApiService: MastodonApiService) {
    }

    getFollowingsForAccount(instanceName: string, accessToken: string, accountId: string, url: string = ''): Observable<[nextLink: string, accounts: Account[]]> {
        if (url === '') {
            url = `https://${instanceName}/api/v1/accounts/${accountId}/following?limit=80`;
        }
        return this.mastodonApiService
            .getAuthenticatedWithResponseHeaders<GetAccountResponse[]>(url, accessToken)
            .pipe(
                map((response) => {
                    const links = response.headers.get('link');
                    let rel = '';
                    let nextUrl = '';
                    if (links) {
                        const nextLink = links!.split(',')[0];
                        rel = nextLink.split(';')[1].replace(' rel="', '').replace('"', '');
                        nextUrl = nextLink.split(';')[0].replace('<', '').replace('>', '');
                    }

                    const accounts = response.body!.map((response) => {
                        return <Account>{
                            id: response.id,
                            username: response.username,
                            acct: response.acct,
                            displayName: response.display_name,
                            note: response.note,
                            url: response.url,
                            avatar: response.avatar,
                            avatarStatic: response.avatar_static,
                            fields: response.fields,
                        };
                    });
                    return [rel === 'next' ? nextUrl : '', accounts];
                })
            );
    }
}
