import { Component, OnInit, Input, ViewChild, ElementRef,
    ChangeDetectorRef, ChangeDetectionStrategy, SimpleChanges, OnChanges } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { UntypedFormGroup, UntypedFormControl, Validators } from '@angular/forms'

import { MatTableDataSource } from '@angular/material/table'

import { AdminDataService } from '../../admin-data.service'
import { AdminBasketFile, AdminBasket } from '../data.service'
import { MatSnackBar } from '@angular/material/snack-bar'
import { HtmlSnackbarComponent } from '../../../custom-snackbar/custom-snackbar.component'

@Component({
    selector: 'gisaf-admin-basket-upload',
    templateUrl: './basket-upload.component.html',
    styleUrls: ['./basket-upload.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AdminBasketUploadComponent implements OnInit, OnChanges {
    constructor(
        public adminDataService: AdminDataService,
        private cdr: ChangeDetectorRef,
        private http: HttpClient,
        private snackBar: MatSnackBar,
    ) {}

    @ViewChild('fileInput') fileInput: ElementRef
    @Input() basket: AdminBasket
    @Input() dataSource: MatTableDataSource<object>

    //upload_fields = ['store', 'status', 'project', 'surveyor', 'equipment']

    formGroup: UntypedFormGroup = new UntypedFormGroup({})

    ngOnInit() {
        let defaults = this.adminDataService.surveyMeta.defaults
        this.formGroup = new UntypedFormGroup({
            'store_misc': new UntypedFormControl(defaults['store_misc'], [Validators.required]),
            'store_line_work': new UntypedFormControl(defaults['store_line_work'], [Validators.required]),
            'status': new UntypedFormControl(defaults['status'], [Validators.required]),
            'project': new UntypedFormControl(defaults['project'], [Validators.required]),
            'surveyor': new UntypedFormControl(defaults['surveyor'], [Validators.required]),
            'equipment': new UntypedFormControl(defaults['equipment'], [Validators.required]),
            'autoImport': new UntypedFormControl(true),
        })
        this.setupRequired()
    }

    ngOnChanges(changes: SimpleChanges) {
        this.setupRequired()
    }

    setupRequired() {
        for (let field in this.formGroup.controls) {
            if (this.basket.uploadFields.includes(field)) {
                this.formGroup.controls[field].setValidators(Validators.required)
            }
            else {
                this.formGroup.controls[field].clearValidators()
            }
            this.formGroup.controls[field].updateValueAndValidity({onlySelf: true})
        }
        this.formGroup.updateValueAndValidity({onlySelf: true})
    }

    onFileUpload() {
        const formData = new FormData()
        formData.append('file', <File>this.fileInput.nativeElement.files[0])
        let fg = this.formGroup.getRawValue()
        for (let field in fg) {
            if (this.basket.uploadFields.indexOf(field) != -1) {
                formData.append(field, fg[field])
            }
        }
        formData.append('autoImport', this.formGroup.get('autoImport').value)
        this.http.post('upload/basket/' + this.basket.name, formData).subscribe(
            resp => {
                let importResult = resp['import_result']
                const importTime = resp['time'] || (importResult && importResult['time'])
                const fileImport = new AdminBasketFile(
                    resp['id'],
                    resp['dir'],
                    resp['name'],
                    resp['url'],
                    resp['md5'],
                    importTime && new Date(importTime),
                    resp['comment'],
                    resp['status'],
                    resp['store'],
                    resp['project'],
                    resp['surveyor'],
                    resp['equipment'],
                )
                this.dataSource.data.push(fileImport)
                this.dataSource.data = this.dataSource.data
                let msg = 'File ' + fileImport.name + ' added to basket'
                if (importResult) {
                    this.snackBar.openFromComponent(HtmlSnackbarComponent, {
                        data: importResult
                        //duration: 3000
                    })

                }
                else {
                    this.snackBar.open(msg, 'Close')
                }
                this.cdr.markForCheck()
            }
        )
    }

    is_upload_field_hidden(fname: string) {
        return this.basket.uploadFields.indexOf(fname)==-1
    }
}