import { signal } from '@angular/core';
import {
    DataTablePageEvent,
    DataTableSortEvent
} from './data-table.types';
import { DataTableQuery } from './data-table.types';

export class DataTableQueryState {
    pageIndex = signal(1);
    pageSize = signal(15);
    searchText = signal('');
    sortColumn = signal('');
    sortDirection = signal<'asc' | 'desc'>('asc');
    private readonly draw = signal(1);

    getQuery(): DataTableQuery {
        return {
            draw: this.draw(),
            page: this.pageIndex(),
            pageSize: this.pageSize(),
            search: this.searchText(),
            sortBy: this.sortColumn(),
            sortDir: this.sortDirection(),
            isActive: null
        };
    }

    setSearch(value: string): DataTableQuery {
        this.searchText.set(value);
        this.pageIndex.set(1);
        this.draw.update(v => v + 1);
        return this.getQuery();
    }

    setPage(event: DataTablePageEvent): DataTableQuery {
        this.pageIndex.set(event.pageIndex);
        this.pageSize.set(event.pageSize);
        this.draw.update(v => v + 1);
        return this.getQuery();
    }

    setSort(event: DataTableSortEvent): DataTableQuery {
        this.sortColumn.set(event.column);
        this.sortDirection.set(event.direction);
        this.pageIndex.set(1);
        this.draw.update(v => v + 1);

        return this.getQuery();
    }

    reset(): DataTableQuery {
        this.pageIndex.set(1);
        this.pageSize.set(15);
        this.searchText.set('');
        this.sortColumn.set('');
        this.sortDirection.set('asc');
        this.draw.set(1);
        return this.getQuery();
    }
}
