import {Component} from '@angular/core';
import {List} from 'projects/mastodon-api/src/public-api';
import {Observable} from "rxjs";
import {select, Store} from "@ngrx/store";
import {selectCurrentInstance, selectLists} from "../../shared/state/store/selectors";
import {FormControl, FormGroup} from "@angular/forms";
import {fromListsPage} from '../../shared/state/store';

@Component({
    selector: 'app-lists',
    templateUrl: './lists.component.html',
    styleUrls: ['./lists.component.scss']
})
export class ListsComponent {

    lists$: Observable<ReadonlyArray<List>>;
    instanceName$: Observable<string | undefined>;
    creatingList: boolean = false;

    newListForm = new FormGroup({
        title: new FormControl(''),
    });

    constructor(private store: Store) {
        this.instanceName$ = this.store.pipe(select(selectCurrentInstance));
        this.lists$ = this.store.pipe(select(selectLists));
    }

    listNameChanged(id: string, event: Event) {
        const target = event.target as HTMLInputElement;
        const newTitle = target.value;
        this.store.dispatch(fromListsPage.updateList({listId: id, newTitle}));
    }

    createList() {
        let title = this.newListForm.value.title ?? '';
        if (title.length > 0) {
            this.store.dispatch(fromListsPage.createList({title}));
            this.newListForm.reset();
        }
    }
}
