import { Component, OnInit, Input, ViewChild, ElementRef,
    ChangeDetectorRef, ChangeDetectionStrategy, SimpleChanges, OnChanges } from '@angular/core'
import { FormGroup, Validators, FormControl } from '@angular/forms'

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

import { AdminDataService } from '../../admin-data.service'
import { AdminBasket, AdminService, FileImport } from '../../../openapi'
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 snackBar: MatSnackBar,
        public adminService: AdminService,
    ) {}

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

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

    formGroup: FormGroup = new FormGroup({})

    ngOnInit() {
        const sm = this.adminDataService.surveyMeta
        const dflt = sm.default
        const dfltProject: number = sm.projects.find(e => e['name'] == dflt.project)?.id
        const dfltSurveyor: number = sm.surveyors.find(e => e['name'] == dflt.surveyor)?.id
        const dfltEquipment: number = sm.equipments.find(e => e['name'] == dflt.equipment)?.id
        this.formGroup = new FormGroup({
            'store_misc': new FormControl(dflt['store_misc'], [Validators.required]),
            'store_line_work': new FormControl(dflt['store_line_work'], [Validators.required]),
            'status': new FormControl(dflt.status, [Validators.required]),
            'project': new FormControl(dfltProject, [Validators.required]),
            'surveyor': new FormControl(dfltSurveyor, [Validators.required]),
            'equipment': new FormControl(dfltEquipment, [Validators.required]),
            'autoImport': new FormControl(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() {
        this.adminService.uploadBasketFileApiAdminBasketUploadNamePost({
            name: this.basket.name,
            equipmentId: this.formGroup.get('equipment').value,
            projectId: this.formGroup.get('project').value,
            surveyorId: this.formGroup.get('surveyor').value,
            autoImport: this.formGroup.get('autoImport').value,
            formData: {
                file: <File>this.fileInput.nativeElement.files[0]
            }
        }).subscribe(
            resp => {
                this.dataSource.data.push(resp.fileImport)
                this.dataSource.data = this.dataSource.data
                if (resp.details) {
                    this.snackBar.openFromComponent(HtmlSnackbarComponent, {
                        data: resp.details
                        //duration: 3000
                    })

                }
                else {
                    let msg = 'File ' + resp.fileImport.name + ' added to basket'
                    this.snackBar.open(msg, 'Close')
                }
                this.cdr.markForCheck()
            }
        )
    }

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