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 {selectLists} from "../../shared/state/store/selectors";
import {PersistentStore} from "../../shared/state/persistent/persistent-store.service";
import {ListActions} from "../../shared/state/store/actions";
import {FormControl, FormGroup} from "@angular/forms";

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

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

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

    constructor(private store: Store, private persistentStore: PersistentStore) {
        this.instanceName = persistentStore.value.currentInstance.instanceName;
        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(ListActions.updateList({listId: id, newTitle}));
    }

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