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 {fromListsPage, fromSyncPage, selectCurrentInstance, selectLists, selectLoading} from "../../shared/state/store";
import {FormControl, FormGroup} from "@angular/forms";
import {SortEvent} from "primeng/api";

@Component({
    selector: 'app-lists',
    templateUrl: './lists.component.html',
    styleUrls: ['./lists.component.scss']
})
export class ListsComponent {
    loading$: Observable<boolean>;
    lists$: Observable<List[]>;
    instanceName$: Observable<string | undefined>;
    creatingList: boolean = false;
    editModels: { [s: string]: List; } = {}

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

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

    customSort(event: SortEvent) {
        console.log(event);
        if (event.field == 'id') {
            return event.data!.sort((a, b) => {
                if (event.order == 1) {
                    return parseInt(a['id']) >= parseInt(b['id']) ? 1 : -1;
                }
                return parseInt(a['id']) < parseInt(b['id']) ? 1 : -1;
            });
        }
        return event.data!.sort((a, b) => {
            if (event.order == 1) {
                return a[event.field!] >= b[event.field!] ? 1 : -1;
            }
            return a[event.field!] < b[event.field!] ? 1 : -1;
        });
    }

    onRowEditInit(list: List) {
        this.editModels[list.id] = {...list};
    }

    onRowEditSave(list: List) {
        const newTitle = this.editModels[list.id].title;
        this.store.dispatch(fromListsPage.updateList({listId: list.id, newTitle}));
        delete this.editModels[list.id];
    }

    onRowEditCancel(list: List) {
        delete this.editModels[list.id];
    }

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

    loadLists() {
        this.store.dispatch(fromSyncPage.loadLists());
    }
}
