import {Component} from '@angular/core';
import {map, Observable} from "rxjs";
import {Account} from "../../../../../mastodon-api/src/lib/interfaces/public/account";
import {List} from "../../../../../mastodon-api/src/lib/interfaces/public/list";
import {select, Store} from "@ngrx/store";
import {selectFilteredFollowingsWithLists, selectLists} from "../../shared/state/store/selectors";
import {ListActions} from "../../shared/state/store/actions";

interface DataGridRow {
    id: string;
    url: string;
    displayName: string;
    username: string;
    avatar: string;
    note: string;
    fields: string;
    lists: List[];
}

@Component({
    selector: 'app-table',
    templateUrl: './table.component.html',
    styleUrls: ['./table.component.scss']
})
export class TableComponent {
    rows$: Observable<DataGridRow[]>;
    lists$: Observable<ReadonlyArray<List>>;

    constructor(private store: Store) {
        this.rows$ = this.store
            .pipe(
                select(selectFilteredFollowingsWithLists),
                map((accounts: ReadonlyArray<Account>) => {
                    return accounts.map((account) => {
                        return {
                            id: account.id,
                            username: `@${account.acct}`,
                            displayName: account.displayName,
                            url: account.url,
                            avatar: account.avatar,
                            note: account.note,
                            fields: account.fields.map(field => `${field.name}: ${field.value}`).join('<br>'),
                            lists: account.lists,
                        } as DataGridRow;
                    });
                }),
            );
        this.lists$ = this.store.pipe(select(selectLists));
    }

    addAccountToSelectedList(accountId: string, listId: string) {
        this.store.dispatch(ListActions.addAccountToList({accountId, listId}));
    }

    removeAccountFromList(accountId: string, listId: string) {
        this.store.dispatch(ListActions.removeAccountFromList({accountId, listId}));
    }
}
