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 { AdminBasketDataService, AdminBasket, AdminBasketFile } from './data.service'
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,
        public adminBasketDataService: AdminBasketDataService,
        private route: ActivatedRoute,
        private snackBar: MatSnackBar,
        private cdr: ChangeDetectorRef,
    ) {}

    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: AdminBasketFile) {
        window.open('/download/basket/' + this.basket.name + '/' + item.id + '/' + item.name)
    }

    importItem(item: AdminBasketFile, dryRun: boolean) {
        this.adminBasketDataService.importItem(this.basket.name, item.id, dryRun).subscribe(
            resp => {
                this.basket.files.find(row => row.id == item.id).time = new Date(resp.time)
                this.snackBar.openFromComponent(HtmlSnackbarComponent, {
                    data: resp,
                    //duration: 3000
                })
                this.cdr.markForCheck()
            }
        )
    }

    deleteItem(item: AdminBasketFile) {
        this.adminBasketDataService.deleteItem(this.basket.name, 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)
    }
}