import {Component} from '@angular/core';
import {map, Observable} from "rxjs";
import {select, Store} from "@ngrx/store";
import {fromListViewPage, fromTableViewPage, selectFilteredFollowingsWithLists, selectLists} from "../../shared/state/store";
import {Account, List} from 'projects/mastodon-api/src/public-api';
import {MultiSelect} from "primeng/multiselect";
import {FilterService} from "primeng/api";

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<List[]>;
    filterByListName = 'filter-by-lists';

    constructor(private store: Store, private filterService: FilterService) {

        this.filterService.register(this.filterByListName, (value: List[], filter: string[]): boolean => {
            console.log(filter);
            if (!filter || filter.length === 0) {
                return true;
            }
            if (filter && filter.length === 1 && filter[0] === '0') {
                console.log('here');
                return value.length === 0;
            }
            return value.some(list => filter.includes(list.id));
        });

        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, select: MultiSelect) {
        select.value.forEach((listId: string) => {
            this.store.dispatch(fromListViewPage.addAccountToList({accountId, listId}));
        });
    }


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