import {
  Component, OnInit, Input, ViewChild, ElementRef,
  ChangeDetectorRef, ChangeDetectionStrategy
} from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { UntypedFormGroup, UntypedFormControl } from '@angular/forms'

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 { AdminDataService } from '../admin-data.service'
import { AdminBasket, AdminService, FileImport } from '../../openapi'
import { HtmlSnackbarComponent } from '../../custom-snackbar/custom-snackbar.component'

@Component({
  selector: 'gisaf-admin-basket',
  templateUrl: './basket.component.html',
  styleUrls: ['./basket.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AdminBasketComponent implements OnInit {
  constructor(
    public adminDataService: AdminDataService,
    private route: ActivatedRoute,
    private snackBar: MatSnackBar,
    private cdr: ChangeDetectorRef,
    public adminService: AdminService,
  ) { }

  basket: AdminBasket
  dataSource: MatTableDataSource<object>
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator
  @ViewChild(MatSort, { static: true }) sort: MatSort
  selection = new SelectionModel(true, [])
  unlockDeleteFormGroup: UntypedFormGroup = new UntypedFormGroup({})
  columns: string[] = [
    'name',
    'status',
    'time',
    'store',
    'project',
    'surveyor',
    'equipment',
    'import',
    'delete',
  ]
  filterText: string

  ngOnInit() {
    this.route.data.subscribe(
      (basket: object) => {
        this.basket = basket['basket']
        this.dataSource = new MatTableDataSource(this.basket.files)
        this.dataSource.sort = this.sort
        this.dataSource.paginator = this.paginator
        this.cdr.markForCheck()
      }
    )
    this.unlockDeleteFormGroup = new UntypedFormGroup({
      'canDelete': new UntypedFormControl(),
    })
  }

  getColumns() {
    return this.columns.filter(
      col => this.basket.columns.indexOf(col) != -1
    )
  }

  applyFilter() {
    this.dataSource.filter = this.filterText.trim().toLowerCase()
  }

  download(item: FileImport) {
    window.open('/api/admin/basket/download/' + this.basket.name + '/' + item.id + '/' + item.name)
  }

  importItem(item: FileImport, dryRun: boolean) {
    return this.adminService.importBasketFileApiAdminBasketImportBasketFileIdGet({
      basket: this.basket.name,
      fileId: item.id,
      dryRun: dryRun
    }).subscribe({
      next: resp => {
        this.basket.files.find(row => row.id == item.id).time = new Date(resp.time).toString()
        this.snackBar.openFromComponent(HtmlSnackbarComponent, {
          data: resp,
          //duration: 3000
        })
        this.cdr.markForCheck()
      },
      error: err => {
        this.snackBar.open(
          `Cannot import: ${err.body['detail'] || err.message || err.statusText}`,
          'Got it',
          { 'politeness': 'assertive' }
        )
      }
    })
  }

  deleteItem(item: FileImport) {
    return this.adminService.deleteBasketFileApiAdminBasketDeleteBasketFileIdGet({
      basket: this.basket.name,
      fileId: item.id
    }).subscribe(
      id => {
        let dsi = this.dataSource.data.findIndex(fi => fi['id'] == id)
        this.dataSource.data.splice(dsi, 1)
        // Force Angular change detection (??)
        this.dataSource.data = this.dataSource.data
        this.cdr.markForCheck()
      }
    )
  }

  isDate(val: any) {
    return val instanceof Date && isFinite(<any>val)
  }
}
