import {Component, TemplateRef, ViewChild} from '@angular/core';
import {PersistentStore} from "../../shared/state/persistent/persistent-store.service";
import {Account} from "../../../../../mastodon-api/src/lib/interfaces/public/account";
import {List} from "../../../../../mastodon-api/src/lib/interfaces/public/list";
import {ListService} from "../../shared/services/list.service";
import {Observable} from "rxjs";
import {select, Store} from "@ngrx/store";
import {selectFilteredFollowingsWithLists, selectLists} from "../../shared/state/store/selectors";
import {ListActions} from "../../shared/state/store/actions";
import {NbDialogService} from "@nebular/theme";

@Component({
    selector: 'app-matrix',
    templateUrl: './matrix.component.html',
    styleUrls: ['./matrix.component.scss']
})
export class MatrixComponent {
    @ViewChild('dialog', {static: true}) dialog: TemplateRef<any> | undefined;
    followings$: Observable<ReadonlyArray<Account>>;
    lists$: Observable<ReadonlyArray<List>>;
    selectedAccount: Account | undefined;

    constructor(private store: Store, private dialogService: NbDialogService) {
        this.followings$ = this.store.pipe(select(selectFilteredFollowingsWithLists));
        this.lists$ = this.store.pipe(select(selectLists));
    }

    openMoreInfo(account: Account) {
        this.selectedAccount = account;
        this.dialogService.open(this.dialog!);
    }

    isChecked(lists: List[], id: string): boolean {
        return lists.some(list => list.id === id);
    }

    onCheckedChange($event: boolean, accountId: string, listId: string) {
        if ($event) {
            this.store.dispatch(ListActions.addAccountToList({accountId, listId}));
        } else {
            this.store.dispatch(ListActions.removeAccountFromList({accountId, listId}));
        }
    }
}
