import { Component, Input, Output, EventEmitter } from '@angular/core'

import { UntypedFormGroup, UntypedFormControl } from '@angular/forms'
import { MatSnackBar } from '@angular/material/snack-bar'

import { DataService } from '../../_services/data.service'
import { AuthenticationService } from '../../_services/authentication.service'
import { ActionsService, Action } from '../../_services/actions.service'

import { FullInfo, InfoDataService, ModelAction } from '../info-data.service'

@Component({
    selector: 'gisaf-info-tools',
    templateUrl: './tools.component.html',
    styleUrls: ['./tools.component.css'],
    providers: [
        DataService,
    ]
})
export class ToolsComponent {
    formGroup: UntypedFormGroup
    actions: Action[] = []
    _source: FullInfo

    @Input() source: FullInfo
    @Output() shouldRefresh: EventEmitter<void> = new EventEmitter<void>()

    constructor(
        private dataService: DataService,
        private infoDataService: InfoDataService,
        private actionsService: ActionsService,
        private snackBar: MatSnackBar,
        public authenticationService: AuthenticationService
    ) {
    }

    ngOnInit() {
        this.infoDataService.dataProviderService$.subscribe(
            (source: FullInfo) => {
                this._source = source
                this.formGroup = new UntypedFormGroup({})
                this.getFormFields(this.formGroup, source)
            }
        )
        this.actionsService.actionsProviderService$.subscribe(
            actions => {
                let storeActions = actions.find(
                    a => a.store == this._source.modelInfo.store
                )
                this.actions = storeActions ? storeActions.actions : []
            }
        )
    }

    getFormFields(formGroup: UntypedFormGroup, fullInfo: FullInfo): object[] {
        // Return the form fields and build the FormGroup controls accordingly
        let formFields = []
        fullInfo.modelInfo.formFields.forEach(
            field => {
                let control = new UntypedFormControl(field.name) //, field.validator)
                formGroup.addControl(field.name, control)
                formFields.push(field)
            }
        )
        return formFields
    }

    executeAction(action: ModelAction, fullInfo: FullInfo) {
        this.actionsService.execute(
            [fullInfo.modelInfo.store],
            [[fullInfo.featureInfo.id.toString()]],
            [action.name],
            []
        ).subscribe(
            results => {
                let result = results[0].actionResults[0]
                if (result.message) {
                    this.snackBar.open(result.message, 'Close', {duration: 3000})
                }
            }
        )
    }
}