import {
  Component, Input, ViewChild, OnInit, HostBinding,
  ChangeDetectorRef, ChangeDetectionStrategy
} from '@angular/core'
import { ActivatedRoute, ParamMap, Router } from '@angular/router'

import { SelectionModel } from '@angular/cdk/collections'
import { MatPaginator } from '@angular/material/paginator'
import { MatSnackBar } from '@angular/material/snack-bar'
import { MatSort } from '@angular/material/sort'
import { MatTableDataSource } from '@angular/material/table'

import { map, switchMap } from 'rxjs/operators'

import { slideInDownAnimation } from '../../animations'

import { ModelDataService, ModelIntrospection, FieldIntrospection } from '../../_services/apollo.service'
//import { TableDataSource } from './datasource'

@Component({
  selector: 'gisaf-admin-list',
  templateUrl: './admin-list.component.html',
  styleUrls: ['./admin-list.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [slideInDownAnimation]
})
export class AdminListComponent implements OnInit {
  /*
  @HostBinding('@slideInDownAnimation') slideInDownAnimation = true
  @HostBinding('style.display')   display = 'block'
  @HostBinding('style.position')  position = 'absolute'
   */

  dataSource: MatTableDataSource<object>
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator
  @ViewChild(MatSort, { static: true }) sort: MatSort
  model: ModelIntrospection
  allColumns: string[] = []
  pageIndex: number
  pageSize: number
  selection = new SelectionModel(true, [])

  constructor(
    protected route: ActivatedRoute,
    protected router: Router,
    protected dataService: ModelDataService,
    public snackBar: MatSnackBar,
    private cdr: ChangeDetectorRef,
  ) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.setModel(params['modelName'])
    })
  }

  setModel(modelName) {
    if (!modelName) {
      return
    }
    this.dataService.introspect(modelName).subscribe(
      res => {
        this.model = res
        this.allColumns = ['select', 'actions'].concat(this.model.columns())
        this.getData()
      },
    )
  }

  getData() {
    this.dataService.all(this.model).pipe(map(data => {
      return data[this.model.name]
    })).subscribe({
      next: data => {
        if (data) {
          this.dataSource = new MatTableDataSource(data)
          this.dataSource.paginator = this.paginator
          this.dataSource.sort = this.sort
        }
        else {
          this.dataSource = new MatTableDataSource([])
        }
        this.cdr.markForCheck()
      },
      error: err => {
        this.snackBar.open(err, 'close', { duration: 3000 })
      }
    })
  }

  /** Whether the number of selected elements matches the total number of rows. */
  isAllSelected() {
    const numSelected = this.selection.selected.length
    const numRows = this.dataSource.data.length
    return numSelected === numRows
  }

  /** Selects all rows if they are not all selected; otherwise clear selection. */
  masterToggle() {
    this.isAllSelected() ?
      this.selection.clear() :
      this.dataSource.data.forEach(row => this.selection.select(row))
  }

  applyFilter(target: EventTarget) {
    let filterValue = target['value']
    this.dataSource.filter = filterValue.trim().toLowerCase()

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage()
    }
  }

  showDetail(item) {
    this.router.navigate(['/admin/model', this.model.name, item[this.model.pkFields()[0].name]])
  }

  add() {
  }

  deleteSelected() {
  }
}
