// import { Directive, ViewChild } from '@angular/core';
// import { MatPaginator } from '@angular/material/paginator';
// import { MatSort } from '@angular/material/sort';
// import { MatTableDataSource } from '@angular/material/table';
// import { environment } from 'src/environments/environment';
// @Directive()
// export class BaseList {
//     isProduction = environment.production
//     @ViewChild(MatSort,{ static: true }) sort: MatSort;
//     @ViewChild(MatPaginator,{ static: true }) paginator: MatPaginator;
//     protected updateMatTable(res: any){
//         res = new MatTableDataSource(res)
//         res.paginator = this.paginator
//         res.sort = this.sort
//         return res
//     }

//     getIndex(i){
//       return this.paginator.pageIndex * this.paginator.pageSize + i + 1
//     }
// }

import { Observable } from 'rxjs';
import { Directive, Output, ViewChild, EventEmitter } from '@angular/core';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { environment } from 'src/environments/environment';
import { map, startWith } from 'rxjs/operators';



export interface ResultPageEvent<T> {
    results: T[];
    current_page: number;
    page_count: number;
    page_size: number;
    row_count: number;
    first_row_on_page: number;
    last_row_on_page: number;
}

export interface CustomeEventPage extends PageEvent {
    queryStringPage?: string,
    paginator?: MatPaginator
}

@Directive()
export class BaseList {
    protected INT_PAGING:CustomeEventPage = {
            length: 0,
            pageIndex: 0,
            pageSize: 5,
            previousPageIndex: null,
            queryStringPage: `0/5`,
    }
    isProduction = environment.production
    @ViewChild(MatSort,{ static: true }) sort: MatSort;
    @ViewChild(MatPaginator,{ static: true }) paginator: MatPaginator;
    @Output() onPaginatorPageChange = new EventEmitter<PageEvent>()

    protected updateMatTable(res: any){
      
      if(res instanceof Array){
        res = new MatTableDataSource(res)
        res.paginator = this.paginator
        res.sort = this.sort
        return res
      }
      return res
    }

    protected updatePagingMatabe<T>(data: ResultPageEvent<T>){
        this.paginator.length = data.row_count
        return data.results
    }



    protected getEventPage(): Observable<PageEvent> {
        return this.paginator.page.pipe(
            startWith(this.INT_PAGING),
            map( event => {
                return {
                    ...event,
                    paginator: this.paginator,
                    queryStringPage: `${event.pageIndex + 1}/${event.pageSize}`
                }
            })
        )
    }

    getIndex(i){
      return this.paginator.pageIndex * this.paginator.pageSize + i + 1
    }

}

